【问题标题】:Are absolute positions in canvas always based on viewport?画布中的绝对位置是否始终基于视口?
【发布时间】:2016-04-05 03:54:15
【问题描述】:

我了解绝对坐标视口坐标之间的区别。

当您指定坐标时,例如画布中的 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("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)

【问题讨论】:

  • 位置相对于画布本身的左上角。

标签: javascript html canvas viewport


【解决方案1】:

两者都不是。画布坐标基于画布本身的左上角。

这一切都是不必要的..

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)
    };
}

【讨论】:

  • 准确来说,Canvas坐标是基于其上下文的变换矩阵,默认为左上角(1,0,0,1,0,0)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-14
  • 1970-01-01
  • 2021-04-23
  • 2018-05-24
  • 2023-04-08
  • 2018-12-02
  • 2013-08-13
相关资源
最近更新 更多