我有一个带网格的画布,如果用户点击一个矩形,它应该用颜色填充。我正在做的是检查用户是否点击了已经着色的矩形,因此程序可以删除它或更改其颜色。
小提琴: http://jsfiddle.net/JQd4j/2/
var build_canvas = document.getElementById("builder-canvas");
var build_context = build_canvas.getContext("2d");
var builder = function () {
var x;
for (x = 0.5; x <= 800; x += 15) {
build_context.moveTo(x, 0);
build_context.lineTo(x, 390);
}
var y;
for (y = 0.5; y < 400; y += 10) {
build_context.moveTo(0, y);
build_context.lineTo(796, y);
}
build_context.strokeStyle = "#000000";
build_context.stroke();
};
builder();
build_context.fillStyle = 'red';
build_canvas.onclick = function (e) {
var rect = build_canvas.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
x = Math.floor((x / 15)) * 15;
y = Math.floor((y / 10)) * 10;
build_context.fillRect(x + 1, y + 1, 14, 9);
}
提前谢谢。
答案 0 :(得分:4)
创建一个与网格对应的数组。单击时,只需将数组的值设置为初始值以外的其他值。
初始化一个包含列数x行数的数组:
var cols = 27;
var rows = 40;
var clicked = new Uint8Array(cols * rows); // initialized with 0
然后简单地计算该数组中单元格的索引并检查一个值,例如1:
build_canvas.onclick = function (e) {
var rect = build_canvas.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top,
cellX = (x / 15)|0, // get hor. cell position
cellY = (y / 10)|0, // get ver. cell position
index = cols * cellY + cellX; // get array index
if (clicked[index] === 1) { // clicked ? (===1)
alert('clicked already'); // do some action
return;
}
clicked[index] = 1; // is clicked now...
x = cellX * 15; // get pixel position
y = cellY * 10;
build_context.fillRect(x + 1, y + 1, 14, 9);
}
<强> Modified fiddle 强>
表示2D数组的1维数组的索引始终计算为width x y position + x position
。
答案 1 :(得分:1)
另一种方法是,通过检查您尝试绘制的颜色:
var p = build_context.getImageData(x+1, y+1, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
if(hex=='#000000'){
build_context.fillRect(x + 1, y + 1, 14, 9);
}else{
//do something
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}