I am trying to make a game using the canvas in Javascript. Currently I have this code:
let context = canvas.getContext('2d');
let gridSize = 5;
let blockInformation = [
{type: 'spawn', size: gridSize, color: 'blue'}, // 0
{type: 'block', size: gridSize, color: 'black'}, // 1
{type: 'lava', size: gridSize - (gridSize * .2), color: 'red'} //2
];
let level = [
{type: 0, x: 1, y: 5},
{type: 1, x: 1, y: 3},
{type: 1, x: 2, y: 3},
{type: 1, x: 4, y: 3},
{type: 1, x: 6, y: 7},
{type: 2, x: 1, y: 4},
{type: 1, x: 7, y: 6},
];
function draw(x, y, sizeX,sizeY) {
context.fillRect(x, canvas.height - sizeY - y, sizeX, sizeY)
}
function drawLevel (level) {
for (let i = 0; i < level.length; i++) {
let lvl = level[i];
let info = blockInformation[lvl.type];
context.fillStyle = info.color;
draw(lvl.x * gridSize, lvl.y * gridSize, info.size, info.size)
}
}
drawLevel(level);
html, body {
padding: 0;
margin: 0;
}
.canvas {
image-rendering: -moz-crisp-edges;
image-rendering: -webkit-crisp-edges;
image-rendering: pixelated;
image-rendering: crisp-edges;
border:1px solid #d3d3d3;
width: 100vw;
height: 100vh;
}
<canvas id="canvas" class="canvas"></canvas>
However, if you look at the game in a proper window, you may see that the lava which is supposed to be smaller than a regular block should be "center-aligned" in the grid.
However, when moved any block by a decimal, it stopped working:
let context = canvas.getContext('2d');
let gridSize = 5;
let blockInformation = [
{type: 'spawn', size: gridSize, color: 'blue'}, // 0
{type: 'block', size: gridSize, color: 'black'}, // 1
{type: 'lava', size: gridSize - (gridSize * .2), color: 'red'} //2
];
let level = [
{type: 0, x: 1, y: 5},
{type: 1, x: 1, y: 3},
{type: 1, x: 2, y: 3},
{type: 1, x: 4, y: 3},
{type: 1, x: 6, y: 7},
{type: 2, x: 1, y: 4},
{type: 1, x: 7, y: 6},
];
function draw(x, y, sizeX,sizeY) {
context.fillRect(x, canvas.height - (sizeY/2) - y, sizeX, sizeY)
}
function drawLevel (level) {
for (let i = 0; i < level.length; i++) {
let lvl = level[i];
let info = blockInformation[lvl.type];
context.fillStyle = info.color;
draw(lvl.x * gridSize, lvl.y * gridSize, info.size, info.size)
}
}
drawLevel(level);
html, body {
padding: 0;
margin: 0;
}
.canvas {
image-rendering: -moz-crisp-edges;
image-rendering: -webkit-crisp-edges;
image-rendering: pixelated;
image-rendering: crisp-edges;
border:1px solid #d3d3d3;
width: 100vw;
height: 100vh;
}
<canvas id="canvas" class="canvas"></canvas>
Is this possible to fix? Thanks!