用数学

时间:2015-09-14 11:54:48

标签: javascript animation canvas rotation

我想像这样旋转矩形:

enter image description here

我不想使用save()translate()rotate()restore()。我想用简单的数学来做。这是我已经做过的一个例子:

demo

如何实现?

1 个答案:

答案 0 :(得分:1)

So you basically need to calculate each corner and draw the rectangle using .lineTo() instead of .fillRect().

To rotate a point around origin by angle you need this:

var rotate = function( point, origin, angle) {
    angle = angle * Math.PI / 180.0;
    return {
        x: Math.cos(angle) * (point.x-origin.x) - Math.sin(angle) * (point.y -origin.y) + origin.x,
        y: Math.sin(angle) * (point.x-origin.x) + Math.cos(angle) * (point.y-origin.y) + origin.y
    };
}

Then define your rectangle corners:

 var corners = [
        { x: 100, y: 0 },
        { x: 150, y: 0 },
        { x: 150, y: 50 },
        { x: 100, y: 50 }
    ];

And render it like this:

    // for example: 
    // origin = { x: 125, y: 175 }, angle = 30;
    ctx.beginPath();
    corners.forEach( function( point ){
        var rotated = rotate( point, origin, angle );
        ctx.lineTo( rotated.x, rotated.y );
    });
    ctx.closePath();
    ctx.fill();

http://jsfiddle.net/grcbab4h/3/

相关问题