如何使用 JavaScript 在单击时为画布坐标网格的背景着色?
如何使用javascript选择多个正方形并单击更改画布上的背景颜色?
到目前为止,我能够“绘制”画布和坐标网格。我无法弄清楚的部分是如何更改选定方块的背景颜色以及如何对多个方块执行相同的操作(用鼠标选择它们)?
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var context = canvas.getContext('2d');
for(var x=0.5;x<500;x+=10) {
context.moveTo(x,0);
context.lineTo(x,500);
}
for(var y=0.5; y<500; y+=10) {
context.moveTo(0,y);
context.lineTo(500,y);
}
context.strokeStyle='grey';
context.stroke();
}
}
function color(event) {
var x = event.clientX - 10;
var y = event.clientY - 10;
console.log(x + ' ' + y);
// how to color the selected squares?
}
#canvas { border: 1px solid black;}
<body onload='draw()'>
<div id=container>
<canvas id='canvas' width='500' height='500' onclick="color(event)"></canvas>
</div>
</body>
How to select multiple squares and on click change their background color on a canvas with javascript?
So far I am able to "draw" the canvas and the coordinate grid. The part I am not able to figure out is how to change the background color of a selected square and how to do the same thing with multiple squares (selecting them with the mouse)?
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var context = canvas.getContext('2d');
for(var x=0.5;x<500;x+=10) {
context.moveTo(x,0);
context.lineTo(x,500);
}
for(var y=0.5; y<500; y+=10) {
context.moveTo(0,y);
context.lineTo(500,y);
}
context.strokeStyle='grey';
context.stroke();
}
}
function color(event) {
var x = event.clientX - 10;
var y = event.clientY - 10;
console.log(x + ' ' + y);
// how to color the selected squares?
}
#canvas { border: 1px solid black;}
<body onload='draw()'>
<div id=container>
<canvas id='canvas' width='500' height='500' onclick="color(event)"></canvas>
</div>
</body>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
维持一个状态是个好主意。在这里,我开始创建一个保存对象的二维数组(数组的数组)。对象的状态可以选择=true|false。
在draw()函数中,我迭代数组并根据对象的状态设置fillStyle。
在 color() 函数中,我计算对象的索引并将所选属性设置为 true。然后我再次绘制画布。
It is a good idea to maintain a state. Here I start off creating an two dimensional array (an array of arrays) that holds an object. The state of the object can be selected=true|false.
In the draw() function I iterate the array and set the fillStyle according to the state of the object.
In the color() function I calculate the index of an object and set the selected property to true. And then I draw the canvas again.