[英]how to fill a cell on clicking the grid on canvas in html5
I want to fill a grid cell on clicking on the particular cell.Here is my code: 我想在单击特定单元格时填充一个网格单元格,这是我的代码:
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>
I edited the drawBox()
function a bit to increase efficiency, also. 我也编辑了drawBox()
函数以提高效率。
e.offsetX
is the mouse coordinate, devide by 40
, then Math.floor()
this to get the cell number, then multiply by 40
to get the starting coordinate of the cell. e.offsetX
是鼠标坐标,除以40
,然后使用Math.floor()
来获取单元格编号,然后乘以40
以获取该单元格的起始坐标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.