获取页面上的HTML5画布的坐标 [英] Obtain co-ordinates of an HTML5 canvas on a page

查看:424
本文介绍了获取页面上的HTML5画布的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在另一个画布中有一个画布。

I have a a canvas inside another canvas.

  <canvas id ='canvas2' height="718" width="1316"></canvas>

其css是某些

#canvas2{
position:absolute;
width :95%;
height:90%;
top:5%;
left:2.5%;
background: #ffff56;
cursor:pointer;

}

下面我画了一些矩形。我需要用鼠标点击颜色。我使用了一个动作监听器。

next I have drawn some rectangles on it. I need to colour those with mouse click. I used an action listener.

var canvas = document.getElementById("canvas2");
var ctx = canvas.getContext("2d");
canvas.addEventListener("mousedown", doMouseDown, false);
var $canvas = $("#canvas2");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
function doMouseDown(event){
event.preventDefault();
event.stopPropagation();
 var x= parseInt(event.clientX - offsetX);
 var y = parseInt(event.clientY - offsetY);
}

但这不是我所知道的正确方法, x和y上的画布坐标。

But this is not the right way I know as I am getting all the wrong canvas co-ordinates on x and y. Can someone show the right way?

推荐答案

你的画布是否已经滚动?

Has your canvas been scrolled?

如果是,那么您还需要考虑画布在浏览器中滚动的距离。

If yes, then you also need to account for the distance the canvas has been scrolled in the browser.

您可以检查canvas.getBoundingClientRect()作为一种方式来获取画布位置,滚动条件:

You might check out canvas.getBoundingClientRect() as a way to get the canvas position with the scrolling accounted for:

function handleMousemove(e){

     e.preventDefault();
     e.stopPropagation();

     // if the canvas is stationary (not scrolling) then you can do
     // .getBoundingClientRect once at the start of the app

     var BB=canvas.getBoundingClientRect();

     // calc mouse position based on the bounding box

     var mouseX=parseInt(e.clientX-BB.left);
     var mouseY=parseInt(e.clientY-BB.top);

     console.log(mouseX+"/"+mouseY);

}

这篇关于获取页面上的HTML5画布的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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