HTML5 Canvas 无法正确显示点击次数
HTML5 Canvas wont show clicks correctly
基本上,我有一个代码可以显示用户点击 canvas:
canvas.onclick = function(e){
ctx.fillRect(e.clientX,e.clientY,10,10);
}
如果我在代码中包含这个,它会工作得很好:
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
但是我想要 canvas 的宽度和高度是 200!像这样:
canvas.width = 200;
canvas.height = 200;
每当我尝试这个时,点击都出错了!如何在不调整全屏 canvas 或 window 的情况下将宽度设置为 200???
我认为你所缺少的只是减去 canvas 偏移量...
这是一个代码示例
var canvas = document.getElementById('can');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d');
ctx.fillRect(50, 50, 2, 2);
canvas.onclick = function(e) {
r = 10
x = e.clientX - canvas.offsetLeft - r
y = e.clientY - canvas.offsetTop - r
ctx.fillRect(x, y, r, r);
}
body {
margin: 0
}
<canvas id="can" style="border:1px solid #000000;"></canvas>
基本上,我有一个代码可以显示用户点击 canvas:
canvas.onclick = function(e){
ctx.fillRect(e.clientX,e.clientY,10,10);
}
如果我在代码中包含这个,它会工作得很好:
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
但是我想要 canvas 的宽度和高度是 200!像这样:
canvas.width = 200;
canvas.height = 200;
每当我尝试这个时,点击都出错了!如何在不调整全屏 canvas 或 window 的情况下将宽度设置为 200???
我认为你所缺少的只是减去 canvas 偏移量...
这是一个代码示例
var canvas = document.getElementById('can');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d');
ctx.fillRect(50, 50, 2, 2);
canvas.onclick = function(e) {
r = 10
x = e.clientX - canvas.offsetLeft - r
y = e.clientY - canvas.offsetTop - r
ctx.fillRect(x, y, r, r);
}
body {
margin: 0
}
<canvas id="can" style="border:1px solid #000000;"></canvas>