gpt4 book ai didi

javascript - 如何在html5中单击 Canvas 上的网格来填充单元格

转载 作者:行者123 更新时间:2023-11-28 04:38:04 26 4
gpt4 key购买 nike

我想在单击特定单元格时填充网格单元格。这是我的代码:

 function drawBox()
{
for (var row = 0; row < 14; row ++)
{
for (var column = 0; column < 13; column ++)
{
var x = column * 40;
var y = row * 40;
context.beginPath();
context.rect(x, y, 40, 40);
context.fillStyle = "white";
context.fill();
context.lineWidth = 3;
context.strokeStyle = 'black';
context.stroke();
}
}

}

最佳答案

I've got a working sample here. Code :

var canvas = document.getElementById("canvas"),
c = canvas.getContext("2d"),
boxSize = 40,
boxes = Math.floor(600 / boxSize);
canvas.addEventListener('click', handleClick);
canvas.addEventListener('mousemove', handleClick);

function drawBox() {
c.beginPath();
c.fillStyle = "white";
c.lineWidth = 3;
c.strokeStyle = 'black';
for (var row = 0; row < boxes; row++) {
for (var column = 0; column < boxes; column++) {
var x = column * boxSize;
var y = row * boxSize;
c.rect(x, y, boxSize, boxSize);
c.fill();
c.stroke();
}
}
c.closePath();
}

function handleClick(e) {
c.fillStyle = "black";

c.fillRect(Math.floor(e.offsetX / boxSize) * boxSize,
Math.floor(e.offsetY / boxSize) * boxSize,
boxSize, boxSize);
}

drawBox();
<canvas id="canvas" width="600px" height="600px"></canvas>

我还稍微编辑了 drawBox() 函数以提高效率。

e.offsetX为鼠标坐标,除以40,然后用Math.floor()这个得到单元格号,然后乘以 40 得到单元格的起始坐标。

关于javascript - 如何在html5中单击 Canvas 上的网格来填充单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13990128/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com