在canvas的使用中,经常会用到鼠标进行交互,但是在交互的过程中难免会遇到一些问题,例如,对于一个居中显示的画布,如图所示
众所周知,canvas的绘制过程中,是以画布的左上顶点为原点进行绘制,假如此时使用鼠标点击事件获取画布左上顶点的坐标,得到的结果为
可见,得到的坐标并非是期望中的(0, 0)或者是和(0, 0)相近的值,这是由于鼠标事件是以document的左上角为原点获取坐标的,因此,为了便于canvas和鼠标的交互,需要对坐标进行转换。
考虑canvas中的一个点基于document的坐标(x, y),由文档结构知,假设canvas距离左边缘和上边缘的距离分别为left, top,此点基于canvas的坐标值应当为(x - left, y - top)
代码的实现过程中,需要使用到canvas.getBoundingclientRect()这个函数
var canvasBound = canvas.getBoundingClientRect()
canvas.onmousedown = function(e){
console.log((e.clientX-canvasBound.left) + " , " + (e.clientY-canvasBound.top));
}
此时,点击canvas左上角,得到的坐标为
可见,此时的坐标近似为(0, 0)点,至此,坐标转换完成
完整代码
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>坐标转换</title>
<style>
#canvas{
border: 1px solid #000000;
display:block;
margin:0 auto;
}
</style>
</head>
<body>
<canvas id="canvas">
</canvas>
<script>
window.onload = function(){
var canvas = document.getElementById("canvas");
canvas.width = 400;
canvas.height = 400;
var context = canvas.getContext("2d");
var canvasBound = canvas.getBoundingClientRect()
canvas.onmousedown = function(e){
console.log((e.clientX-canvasBound.left) + " , " + (e.clientY-canvasBound.top));
}
}
</script>
</body>
</html>
如果在工程中使用坐标转换,可以将坐标转换封装在函数中,便于重复使用
function coordinateTrans( x , y ){
var canvasBound = canvas.getBoundingClientRect()
return {x:(x-canvasBound.left) , y:(y-canvasBound.top)}
}