gpt4 book ai didi

javascript - 彼此上方的两个 Canvas 返回不同的 x,y 坐标

转载 作者:行者123 更新时间:2023-12-01 01:51:56 25 4
gpt4 key购买 nike

我在彼此上方绘制了 2 个 Canvas ,在底部加载了图像。我使用顶部 Canvas 进行鼠标移动事件,并根据底部 Canvas 上加载的图像绘制一些信息(例如,当鼠标位于眼睛上方时,我绘制圆圈)。问题是,尽管两个 Canvas 具有相同的宽度和高度,但顶部 Canvas 的 x,y 协调似乎与底部 Canvas 不匹配,我是否遗漏了什么?加载图像后,我尝试将顶部 canvas.scale 设置为如下所示。谢谢!新山

最佳答案

您需要像这样从 Canvas 位置中减去当前鼠标位置

let x = e.clientX - canvasA.offsetLeft
let y = e.clientY - canvasA.offsetTop

这样做将为您提供 Canvas 的本地位置而不是窗口的位置。

这是一个示例(将鼠标移到红色 Canvas 上):

const canvasA = document.getElementById('a')
const canvasB = document.getElementById('b')

let ctxB = canvasB.getContext('2d')

canvasA.addEventListener('mousemove', e => {
ctxB.clearRect(0, 0, canvasB.width, canvasB.height)

// Get the local x/y coordinates of the mouse on the red canvas
let x = e.clientX - canvasA.offsetLeft
let y = e.clientY - canvasA.offsetTop

// Mimic the position on the blue canvas with a white dot
ctxB.beginPath();
ctxB.arc(x, y, 5, 0, 2 * Math.PI, false);
ctxB.fillStyle = 'white';
ctxB.fill();
})
#a {
background-color: red;
}

#b {
background-color: blue;
}
<canvas id="a"></canvas>
<canvas id="b"></canvas>

如果您不计算此值,则会发生以下情况,我在主体顶部添加了填充,如您所见,该点现在比鼠标低50px

const canvasA = document.getElementById('a')
const canvasB = document.getElementById('b')

let ctxB = canvasB.getContext('2d')

canvasA.addEventListener('mousemove', e => {
ctxB.clearRect(0, 0, canvasB.width, canvasB.height)

// Get the local x/y coordinates of the mouse on the red canvas
let x = e.clientX
let y = e.clientY

// Mimic the position on the blue canvas with a white dot
ctxB.beginPath();
ctxB.arc(x, y, 5, 0, 2 * Math.PI, false);
ctxB.fillStyle = 'white';
ctxB.fill();
})
body {padding-top: 50px;}

#a {
background-color: red;
}

#b {
background-color: blue;
}
<canvas id="a"></canvas>
<canvas id="b"></canvas>

如果需要考虑滚动,可以使用document.documentElement.scrollTop

let x = (e.clientX + document.documentElement.scrollLeft) - canvasA.offsetLeft
let y = (e.clientY + document.documentElement.scrollTop) - canvasA.offsetTop

const canvasA = document.getElementById('a')
const canvasB = document.getElementById('b')

let ctxB = canvasB.getContext('2d')

canvasA.addEventListener('mousemove', e => {
ctxB.clearRect(0, 0, canvasB.width, canvasB.height)

// Get the local x/y coordinates of the mouse on the red canvas
let x = (e.clientX + document.documentElement.scrollLeft) - canvasA.offsetLeft
let y = (e.clientY + document.documentElement.scrollTop) - canvasA.offsetTop

// Mimic the position on the blue canvas with a white dot
ctxB.beginPath();
ctxB.arc(x, y, 5, 0, 2 * Math.PI, false);
ctxB.fillStyle = 'white';
ctxB.fill();
})
body {
padding-top: 150vh;
}

#a {
background-color: red;
}

#b {
background-color: blue;
}
<canvas id="a"></canvas>
<canvas id="b"></canvas>

关于javascript - 彼此上方的两个 Canvas 返回不同的 x,y 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51412816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com