这是问题的一个 fiddle :
https://jsfiddle.net/y5cu0pxf/
我已经搜索并尝试了很多,但找不到问题所在。我只想让笔准确地画出鼠标点击的位置,但由于某种原因它发生了偏移。
有什么想法吗?
代码如下:
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = window.innerWidth * 0.5;
canvas.height = window.innerHeight;
var hRatio = canvas.width / img.width;
var vRatio = canvas.height / img.height;
var ratio = Math.min (hRatio, vRatio);
var centerShift_x = (canvas.width - (img.width * ratio)) / 2;
var centerShift_y = (canvas.height - (img.height * ratio)) / 2;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, img.width, img.height,
centerShift_x, centerShift_y, img.width * ratio, img.height * ratio);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
var isDrawing;
var rect = canvas.getBoundingClientRect();
var offsetX = rect.left;
var offsetY = rect.top;
canvas.onmousedown = function(e) {
isDrawing = true;
ctx.moveTo(e.clientX - offsetX, e.clientY - offsetY);
};
canvas.onmousemove = function(e) {
if (isDrawing) {
ctx.lineTo(e.clientX - offsetX, e.clientY - offsetY);
ctx.stroke();
}
};
canvas.onmouseup = function() {
isDrawing = false;
};
最佳答案
Canvas 和鼠标
Canvas 和大小
Canvas 有两个尺寸属性,一个以像素为单位表示分辨率,另一个以 CSS 单位指定显示尺寸。两者相互独立。
// HTML <canvas id = "myCan"><canvas>
// To set the resolution use the canvas width and height properties
myCan.width = 1024;
myCan.height = 1024;
// To set the display size use the style width and height
myCan.style.width = "100%"; // Note you must post fix the unit type %,px,em
myCan.style.height = "100%";
默认情况下, Canvas 分辨率设置为 300 x 150 像素。 Canvas 显示大小将取决于布局和 CSS 规则。
当渲染到 Canvas 2D 上下文时,您在像素坐标而不是样式坐标中渲染。
获取 Canvas 的位置
var canvasBounds = myCan.getBoundingClientRect();
鼠标
鼠标坐标以像素为单位。
使用一个事件处理程序来处理所有鼠标 IO
const mouse = {
x: 0, y: 0, // coordinates
lastX: 0, lastY: 0, // last frames mouse position
b1: false, b2: false, b3: false, // buttons
buttonNames: ["b1", "b2", "b3"], // named buttons
}
function mouseEvent(event) {
var bounds = myCan.getBoundingClientRect();
// get the mouse coordinates, subtract the canvas top left and any scrolling
mouse.x = event.pageX - bounds.left - scrollX;
mouse.y = event.pageY - bounds.top - scrollY;
要获得正确的 Canvas 坐标,您需要缩放鼠标坐标以匹配 Canvas 分辨率坐标。
// first normalize the mouse coordinates from 0 to 1 (0,0) top left
// off canvas and (1,1) bottom right by dividing by the bounds width and height
mouse.x /= bounds.width;
mouse.y /= bounds.height;
// then scale to canvas coordinates by multiplying the normalized coords with the canvas resolution
mouse.x *= myCan.width;
mouse.y *= myCan.height;
然后只获取您感兴趣的其他信息。
if (event.type === "mousedown") {
mouse[mouse.buttonNames[event.which - 1]] = true; // set the button as down
} else if (event.type === "mouseup") {
mouse[mouse.buttonNames[event.which - 1]] = false; // set the button up
}
}
拖动时捕获鼠标(按下按钮)
当为使用 Canvas 的绘图应用程序处理鼠标时,您不能直接将事件监听器添加到 Canvas 。如果你这样做,当用户离开 Canvas 时你会失去鼠标。如果用户在离开 Canvas 时松开鼠标,您将不知道按钮已弹起。结果是按钮卡在了下方。 (就像你的 fiddle 一样)
要捕获鼠标以便获得按下按钮时发生的所有事件,如果用户移动了 Canvas 、离开页面或离开屏幕,则需要收听 文档
的鼠标事件。
所以要添加上面的鼠标事件监听器
document.addEventListener("mousemove", mouseEvent);
document.addEventListener("mousedown", mouseEvent);
document.addEventListener("mouseup", mouseEvent);
现在,mouseEvent
处理所有页面点击,并在按钮按下时将鼠标专门捕获到您的页面。
您可以通过检查 event.target
// only start mouse down events if the users started on the canvas
if (event.type === "mousedown" && event.target.id === "myCan") {
mouse[mouse.buttonNames[event.which - 1]] = true;
}
事件不应呈现
鼠标事件可以非常快速地触发,一些设置以每秒超过 600 个事件触发鼠标移动。如果您使用鼠标事件渲染到 Canvas 上,您将浪费大量 CPU 时间,并且还会在 DOM 同步合成和布局引擎之外渲染。
通过requestAnimationFrame
使用动画循环来绘制。
function mainLoop(time) {
if (mouse.b1) { // is button 1 down?
ctx.beginPath();
ctx.moveTo(mouse.lastX,mouse.lastY);
ctx.lineTo(mouse.x,mouse.y);
ctx.stroke();
}
// save the last known mouse coordinate here not in the mouse event
mouse.lastX = mouse.x;
mouse.lastY = mouse.y;
requestAnimationFrame(mainLoop); // get next frame
}
// start the app
requestAnimationFrame(mainLoop);
这应该让您的绘图应用程序按您希望的方式工作。
关于JavaScript - 在 Canvas 上绘图时鼠标位置错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43853119/