在画布中旋转后坐标问题

时间:2019-02-01 12:01:59

标签: javascript canvas html5-canvas

我在画布上画矩形时遇到了问题。

我的目标是画一张: 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只包含canvas元素,并且我没有使用任何特殊的库。

1 个答案:

答案 0 :(得分:0)

问题是您在块的角上而不是在中心上旋转。下面,我将0.5添加到第一个变换中,然后在旋转后的第二个变换中将其减去。您可以在这里fiddle

看到它的运行情况
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");