使用滚动条后的画布像素坐标偏移 [英] Canvas pixel coordinate offset after scroll bar is used

查看:1167
本文介绍了使用滚动条后的画布像素坐标偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面顶部使用了一个画布。 Im在mousemove事件中从画布中写出像素坐标。通常,最底部的Y值等于画布高度,即。 700px。但是在滚动条用于向下滚动页面上的一点之后,画布中的底部y坐标将相应地改变为400px。

I'm using a canvas at the top of a page. Im writing out the pixel coordinates from the canvas at a mousemove event. Normally, the most bottom Y-value is equal to the canvas height, i e. 700px. But after scrollbar is used to scroll down a bit on the page, the bottom y-coordinate in the canvas will change accordingly to say 400px instead.

            document.getElementById("mapcanvas").addEventListener("mousemove", getPosition, false);

            function getPosition(event)
            {
              var x = event.x;
              var y = event.y;

              var canvas = document.getElementById("mapcanvas");

              x -= canvas.offsetLeft;
              y -= canvas.offsetTop;



             document.getElementById("canvascoords").innerHTML = "Canvascoords: "+ "x=" + x + ", y=" + y;





            }


$ b b

...其中mapcanvas是我的div拿着画布。

... Where "mapcanvas" is my div holding the canvas.

任何使y坐标与使用滚动条无关的想法,以便下面的y坐标始终为700px?

Any ideas of making the y-coordinate independent from usage of scroll bar so that the lower y-coordinate always i 700px?

推荐答案

正如你已经发现的, canvas.offsetLeft & canvas.offsetTop 不考虑滚动。

As you've discovered, canvas.offsetLeft & canvas.offsetTop do not account for scrolling.

要考虑滚动,可以使用 canvas.getBoundingClientRect

To account for scrolling, you can use canvas.getBoundingClientRect

var BB=canvas.getBoundingClientRect();

var x=event.clientX-BB.left;
var y=event.clientY-BB.top;

BTW,你可能想在getPosition()函数之外获取canvas元素的引用而不是在getPosition()内重复提取它。

BTW, you might want to fetch a reference to the canvas element just once outside your getPosition() function instead of fetching it repeatedly inside getPosition().

var canvas = document.getElementById("mapcanvas");

function getPosition(event){

...

这篇关于使用滚动条后的画布像素坐标偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆