【发布时间】:2022-01-02 01:53:03
【问题描述】:
我有一个使用 32x32 瓦片的瓦片集:
我将它绘制在画布上以显示 32x32 平铺地图。但是,数学似乎不对。为什么画布绘制的图块显然不在图块的 32x32 范围内?
例如:
如您所见,画布的 32x32 网格的左上角应该是 ONE tile...但是它被切断了:
const appDiv = document.getElementById('app');
const tileSize = 32;
const canvasSize = 480; // 32 (tiles) * 15 (columns) = 480 pixels
const tilesAcross = canvasSize / tileSize; // (Size of Canvas [480] / Tile size [32]) = 15 columns
appDiv.innerHTML = `<h2>Canvas</h2><canvas id="map" width="${canvasSize}" height="${canvasSize}">`;
function randomIntFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
resizeCanvas();
// Regenerate map on resize
window.onresize = resizeCanvas;
function resizeCanvas() {
const ctx = document.getElementById('map').getContext('2d');
const image = new Image();
image.src = 'https://i.postimg.cc/k4KBLBJh/terrain.png'; // Tileset
image.onload = () => {
for (let column = 0; column < tilesAcross; column++) {
for (let row = 0; row < tilesAcross; row++) {
ctx.drawImage(
image, // Image elemnt
randomIntFromInterval(0, 5) * 32, // sx - The x-axis of top left corner of the rect of the image to draw into context.
randomIntFromInterval(0, 5) * 32, // sy - The y-axis of top left corner of the rect of the image to draw into context.
32, // sWidth - The width of the rect of the image to draw into context.
32, // sHeight - The height of the rect of the image to draw into the destination context.
row * 32, // dx - The x-axis coordinate in the canvas at which to place the top-left corner of the image.
column * 32, // dy - The y-axis coordinate in the canvas at which to place the top-left corner of the image.
32, // dWidth - The width to draw the image in the canvas. This allows scaling of the drawn image.
32 // dHeight- The width to draw the image in the canvas. This allows scaling of the drawn image.
);
}
}
};
}
canvas {
background: black;
}
<div id="app"></div>
<style src="./style.css"></style>
【问题讨论】:
-
您验证了
randomIntFromInterval(0, 5) * 32实际上产生了真值?作为代码的一部分,复制您的ctx.drawImage讲师,将其重命名为console.log,从该代码中删除image参数,然后运行。这些值有意义吗? -
是的,我已验证。即使只有整数 - 也是一样的。
标签: javascript html canvas