我了解绝对坐标视口(viewport)坐标之间的区别。
当您指定坐标时,例如 Canvas 中的 fillText(msg, posX, posY) , posX 和 posY 是视口(viewport)坐标吗?因为尽管指定了精确的坐标,例如 (posX,posY) 的 (50,50),我得到相同的输出,也就是说,即使在调整大小的窗口中,输出字符串也放置在相同的位置。
JS fiddle here
HTML 代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="mycanvas" width="1000" height="1000">
</canvas>
<script src="without.js">
</script>
</body>
</html>
JS代码 var canvas = document.getElementById("mycanvas") var context = canvas.getContext('2d')
function windowToCanvas(x,y)
{
var box = canvas.getBoundingClientRect();
return{
x : (x-box.left) * (canvas.width / box.width),
y : (y-box.top) * (canvas.height / box.height)
};
}
context.font = "30px Arial";
var posX = 50;
var posY = 50;
var loc = windowToCanvas(50,50)
var posX = loc.x;
var posY = loc.y;
context.fillText("Hello World!",posX,posY)
最佳答案
都不是。 Canvas 坐标基于 Canvas 本身的左上角。
这一切都是不必要的..
function windowToCanvas(x,y)
{
return {x:x, y:y};
// You don't need all this
var box = canvas.getBoundingClientRect();
return{
x : (x-box.left) * (canvas.width / box.width),
y : (y-box.top) * (canvas.height / box.height)
};
}
关于javascript - Canvas 中的绝对位置是否始终基于视口(viewport)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34541970/