根据我的期望,画布旋转不会发生

时间:2011-08-10 13:00:17

标签: javascript jquery html5

我希望我的矩形旋转到位。但是目前它正在转动,好像在中心有一个物体,我的物体在它周围旋转,就像我们在太阳系中看到的那样。我希望我的物体在原地旋转而不是围绕某些东西旋转。我怎么能这样做?

到目前为止,这是我的代码:

<script type="text/javascript">
    var context;
    var radian = 0.01;
    var w, h;
    $(document).ready(function () {
        w = document.width;
        h = document.height;
        var canvas = $('#canvas');
        context = canvas[0].getContext('2d');
        canvas[0].width = w;
        canvas[0].height = h;
        setInterval(startAnim, 10);
    });

    function startAnim() {

        context.save();
        context.strokeStyle = 'rgb(0,0,0)';
        context.fillStyle = 'rgb(0,0,0)';
        context.fillRect(0, 0, w, h);

        context.strokeStyle = 'rgb(0,0,0)';
        context.fillStyle = 'rgb(255,255,0)';
        context.strokeRect(0, 0, 200, 200);
        context.fillRect(0, 0, 200, 200);
        context.restore();
        context.fillStyle = 'rgb(0,255,255)';
        context.fillRect(500, 400, 200, 200);
        radian += 0.01;
    }

</script>

更新:抱歉,我在发布之前正在尝试,我忘记在发布时添加旋转功能。这是实际的代码:

function startAnim() {

        context.save();
        context.strokeStyle = 'rgb(0,0,0)';
        context.fillStyle = 'rgb(0,0,0)';
        context.fillRect(0, 0, w, h);

        context.translate(350, 300);
        context.rotate(radian);
        context.translate(-350, -300);

        context.strokeStyle = 'rgb(0,0,0)';
        context.fillStyle = 'rgb(255,255,0)';
        context.strokeRect(0, 0, 200, 200);
        context.fillRect(0, 0, 200, 200);
        context.restore();
        context.fillStyle = 'rgb(0,255,255)';
        context.fillRect(500, 400, 200, 200);
        radian += 0.01;
    }

2 个答案:

答案 0 :(得分:2)

使用translate(x, y)rotate(r),然后绘制矩形。

function startAnim() {
    context.save();
    context.strokeStyle = 'rgb(0,0,0)';
    context.fillStyle = 'rgb(0,0,0)';
    context.fillRect(0, 0, w, h);
    //^Shouldn't clearRect() be better here?

    //Draw translated, rotated rectangle at (250, 250)
    var x = 250;
    var y = 250;
    context.save();
    context.translate(x, y);
    context.rotate(radian);
    context.fillStyle = 'rgb(255,255,0)';
    context.fillRect(0, 0, 200, 200);
    context.restore();
    //Restore context (to reverse translation and rotation)

    context.strokeStyle = 'rgb(0,0,0)';
    context.fillStyle = 'rgb(255,255,0)';
    context.strokeRect(0, 0, 200, 200);
    context.fillRect(0, 0, 200, 200);
    context.restore();
    context.fillStyle = 'rgb(0,255,255)';
    context.fillRect(500, 400, 200, 200);
    radian += 0.01;
}
带有一个旋转矩形的

jsFiddle demoSimple jsFiddle demo

答案 1 :(得分:0)

在旋转之前,您必须将上下文转换为矩形的中心:

context.translate(RECT_CENTER_X, RECT_CENTER_Y);
context.rotate(radian);
context.fillRect(-RECT_CENTER_X, -RECT_CENTER_Y, w, h);