[英]How I can find which grid square element I clicked in HTML5 canvas
我已經使用StrokeLineX和StrokeLineY在html5畫布中繪制了一個網格。 當我在網格中單擊時,我想突出顯示特定的正方形/矩形。 我嘗試使用math.floor定義空間的索引,但是一旦寬度或高度增加,它就會開始給出不同的答案。 在最終將其發布到這里之前,我嘗試了太多次。 這是代碼。
var canvas = document.getElementById("myCanvas");
canvas.addEventListener('click', on_canvas_click, false);
var ctx = canvas.getContext("2d");
var tray_length = 800;
var tray_depth = 800;
var boxHeight = 50;
var boxWidth = 50;
var canvas_X = tray_length;
var canvas_Y = tray_depth;
var box_x_pixels = canvas_X/no_of_columns;
var box_y_pixels = canvas_Y/no_of_rows;
// Drawing the grid
for (var y = boxWidth; y < canvas_Y; y += boxWidth) {
strokeLineX(ctx, y);
}
for (var x = boxHeight; x < canvas_X; x += boxHeight) {
strokeLineY(ctx, x);
}
function strokeLineX(ctx, y) {
ctx.beginPath();
ctx.strokeStyle = 'green';
ctx.moveTo(0, y);
ctx.lineTo(canvas_X, y);
ctx.stroke();
ctx.closePath();
}
function strokeLineY(ctx, x) {
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas_Y);
ctx.stroke();
ctx.closePath();
}
function on_canvas_click(ev) {
var x = ev.pageX - canvas.offsetLeft;
var y = ev.pageY - canvas.offsetTop;
console.log(x+":"+y);
var coordinateDisplay = "x=" + x + ", y=" + y;
if (y>= 0 && y <= y+boxHeight ) {
var indexOfX = Math.floor(x/boxWidth); //divide on width and round off
var indexOfY = Math.floor(y/boxHeight);
// alert('You clicked bar index: ' + indexOfX+"-"+indexOfY);
ctx.fillRect="green";
ctx.rect(x,y,box_x_pixels,box_y_pixels);
ctx.stroke();
console.log(indexOfX + "-" + indexOfY);
}
}
在on_canvas_click
更改以下內容:
代替
ctx.fillRect="green";
做:
ctx.fillStyle="green";
而不是:
ctx.rect(x,y,box_x_pixels,box_y_pixels);
做:
ctx.fillRect(boxWidth*indexOfX, boxHeight*indexOfY, boxWidth, boxHeight);
...而您不需要:
ctx.stroke();
這是一個應用了這些更改的工作片段,但也有一些與您的問題無關的簡化步驟:
canvas.width
和canvas.height
屬性; var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var boxHeight = 50; var boxWidth = 50; var canvas_X = canvas.width; var canvas_Y = canvas.height; canvas.addEventListener('click', on_canvas_click, false); // Drawing the grid for (var y = 0; y <= canvas_Y; y += boxWidth) { strokeLine(ctx, 0, y, canvas_X, y, 'green'); } for (var x = 0; x <= canvas_X; x += boxHeight) { strokeLine(ctx, x, 0, x, canvas_Y, 'red'); } function strokeLine(ctx, x0, y0, x1, y1, color) { ctx.beginPath(); ctx.strokeStyle = color; ctx.moveTo(x0, y0); ctx.lineTo(x1, y1); ctx.stroke(); ctx.closePath(); } function on_canvas_click(ev) { var x = ev.pageX - canvas.offsetLeft; var y = ev.pageY - canvas.offsetTop; if (y>= 0 && y <= y+boxHeight ) { var indexOfX = Math.floor(x/boxWidth); //divide on width and round off var indexOfY = Math.floor(y/boxHeight); ctx.fillStyle="green"; ctx.fillRect(boxWidth*indexOfX, boxHeight*indexOfY, boxWidth, boxHeight); } }
<canvas id="myCanvas" width="600" height="200"></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.