我理解绝对坐标视口坐标之间的区别。
当您在画布中指定坐标时,例如fillText(msg,posX,posY),是posX和posY视口坐标吗?因为尽管为(posX,posY)指定了精确的坐标,例如(50,50),但我得到相同的输出,即输出字符串即使在调整大小的窗口中也放在同一位置。
JS小提琴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(&#34; mycanvas&#34;) var context = canvas.getContext(&#39; 2d&#39;)
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)
答案 0 :(得分:1)
两者都不是。 canvas coords基于画布本身的左上角。
这一切都是不必要的..
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)
};
}