【发布时间】:2020-09-20 16:47:19
【问题描述】:
我跟随Draw on HTML5 Canvas using a mouse在convas中绘制免费共享,提供代码sn-p不能正常工作,但是当我尝试使用时,它不能正常工作。我的意思是光标的位置与画布中的不同。
这里是代码 sn-ps
function init() {
canvas = document.getElementById("whiteboard-canvas");
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
canvas.addEventListener(
"mousemove",
function (e) {
findxy("move", e);
console.log("on mouse move", e);
},
false
);
#othere mouse event handler goes here..
}
function draw() {
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
}
function findxy(res, e) {
if (res == "down") {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;;
currY = e.clientY - canvas.offsetTop;;
flag = true;
dot_flag = true;
if (dot_flag) {
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(currX, currY, 2, 2);
ctx.closePath();
dot_flag = false;
}
}
if (res == "up" || res == "out") {
flag = false;
}
if (res == "move") {
if (flag) {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;;
currY = e.clientY - canvas.offsetTop;;
draw();
}
}
}
我的代码 sn-ps 与链接中的代码几乎相同。
【问题讨论】:
-
首先,JS cmets 不以
#开头 - 这是无效的,当您在浏览器中启动控制台时,您应该立即注意到这一点。其次,从你的 sn-p 你我看不出任何本质上的错误,除了ctx.fillStyle = x;没有意义,x通常是一个坐标,所以用它作为填充没有意义,但因为我不知道x来自哪里,我不能说这是否会导致你的问题。简而言之,将您的变量定义也添加到此帖子中(包括canvas、ctx等...),并将其转换为 SO sn-p(其<>文档图标)。 -
您必须缩放鼠标坐标(以 CSS 像素为单位)以匹配画布分辨率(画布像素)。该示例不包含执行此操作的代码,并且有许多警告。最基本的是
canvasPixelX = currX * (canvas.width / canvas.getBoundingClientRect().width * devicePixelRatio)和高度相同。请参阅developer.mozilla.org/en-US/docs/Web/API/Element/… 正确使用`getBoundingClientRect`和developer.mozilla.org/en-US/docs/Web/API/Window/… for devicePixelRatio -
@Blindman67 这不是真的,
offsetX提供了正确的值,不需要缩放。 -
@somethinghere
offsetX和 Y 给出了左上角,它不提供与 CSS 像素相比画布像素大小的任何信息。画布分辨率与画布显示大小无关。在默认状态下,画布坐标是画布像素而不是 CSS 像素。如果 OP 有视网膜(或许多高清设备之一)显示devicePixelRatio也必须用于正确缩放 -
你在树林里下车,伙计。问题不在于。没有迹象表明这与 DPI 有任何关系。你让问题变得不必要地复杂了。由于没有视网膜指标,所有这些都匹配。即便如此,您也可以使用简单的 context.scale() 来解决这个问题,然后完全忘记它。这家伙刚刚起步,视网膜没有问题。
标签: canvas html5-canvas