首页 > 解决方案 > 在画布中旋转后的坐标问题

问题描述

我在画布上绘制一些矩形时遇到问题。

我的目标是画这个: https ://ibb.co/b6Hsc4w

 0 1 2 3 4 5
0    
1    X X X
2    X   X
3    X X X
4
5
var canvas = document.querySelector('canvas');
canvas.width = 600;
canvas.height = 400;
var c = canvas.getContext('2d');

function Line(x, y, length, height, angle, color) {
    this.x = x;
    this.y = y;
    this.length = length;
    this.height = height;
    this.angle = angle;
    this.color = color;

    this.draw = function () {
        c.save();

        c.translate(this.x, this.y);
        if (this.angle > 0) {
            c.rotate(this.angle * Math.PI / 180);
        }

        c.fillStyle = this.color;
        c.fillRect(0, 0, this.length, this.height);

        c.restore();
    };
    this.draw();
}

new Line(2, 1, 3, 1, 0, "black");
new Line(4, 1, 3, 1, 90, "green");
new Line(4, 3, 3, 1, 180, "red");
new Line(2, 3, 3, 1, 270, "blue");

但使用我收到的代码: https ://ibb.co/vwRX1sG

 0 1 2 3 4 5
0    X
1    X X X
2  X X X  
3      X 
4
5

就像源点无法正常工作一样。

HTML 只包含一个画布元素,我没有使用任何特殊的库。

标签: javascriptcanvashtml5-canvas

解决方案


问题是您在块的角落而不是中心旋转。下面我在第一个变换中添加了 0.5,然后在旋转后的第二个变换中减去它。你可以看到它在这里工作小提琴

function Line(x, y, length, height, angle, color) {
    this.x = x;
    this.y = y;
    this.length = length;
    this.height = height;
    this.angle = angle;
    this.color = color;

    this.draw = function () {
        c.save();

        c.translate(this.x+0.5, this.y+0.5);
        if (this.angle > 0) {
            c.rotate(this.angle * Math.PI / 180);
        }
        c.translate(-0.5, -0.5);

        c.fillStyle = this.color;
        c.fillRect(0, 0, this.length, this.height);

        c.restore();
    };
    this.draw();
}

new Line(2, 1, 3, 1, 0, "black");
new Line(4, 1, 3, 1, 90, "green");
new Line(4, 3, 3, 1, 180, "red");
new Line(2, 3, 3, 1, 270, "blue");

推荐阅读