我有我的画布,单击时得到X和Y,例如x = 10 y = 10,当我使用滚动条拖放并单击相同位置时,我将得到x =不是10和y =不是10。为什么?
<canvas></canvas>
<script>
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
topCanvas = canvas.offsetTop;
leftCanvas = canvas.offsetLeft;
function click(e)
{
console.log("x="+(e.clientX-leftCanvas));
console.log("y="+(e.clientY-topCanvas));
}
</script>
为什么滚动条不起作用。
答案 0 :(得分:0)
let canvas = document.querySelector('canvas');
let topCanvas = canvas.offsetTop;
let leftCanvas = canvas.offsetLeft;
canvas.addEventListener('click', e => {
console.log('not considering scroll position');
console.log(" x=" + (e.clientX - leftCanvas));
console.log(" y=" + (e.clientY - topCanvas));
console.log('considering scroll position');
console.log(" x=" + e.layerX);
console.log(" y=" + e.layerY);
});
div {
border: 1px solid;
max-height: 300px;
overflow: auto;
}
canvas {
border: 1px solid;
width: 500px;
height: 1000px;
margin-left: 30px;
margin-top: 30px;
}
<div>
<canvas></canvas>
</div>
答案 1 :(得分:0)
console.log(“ scroll nie zostal”,(e.clientY-topCanvas)); console.log(“ scroll”,e.layerY);
滚动nie zostal 232 滚动未定义
为什么未定义? 我使用.mousemove。