admin管理员组文章数量:1304960
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 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();
}
}
}
Share
Improve this question
edited Dec 21, 2012 at 12:44
Cerbrus
73k19 gold badges136 silver badges150 bronze badges
asked Dec 21, 2012 at 12:22
Vijeta KaraniVijeta Karani
951 silver badge7 bronze badges
1 Answer
Reset to default 9I'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.
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.
本文标签: javascripthow to fill a cell on clicking the grid on canvas in html5Stack Overflow
版权声明:本文标题:javascript - how to fill a cell on clicking the grid on canvas in html5 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741790879a2397650.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论