我在彼此上方绘制了2个画布,在底部我加载了图像。 我正在使用顶部画布进行鼠标移动事件,并根据底部画布上加载的图像绘制一些信息(例如,当鼠标悬停在眼睛上方时,我绘制了圆圈)。 问题是,尽管两个画布的宽度和高度都相同,但顶部画布的x,y坐标似乎不适合底部画布,我是否丢失了任何东西? 加载图像后,我尝试将顶部canvas.scale设置为一个波纹管。 谢谢! JB
答案 0 :(得分:2)
您需要像这样从画布位置减去当前鼠标位置
let x = e.clientX - canvasA.offsetLeft
let y = e.clientY - 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 - 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>