如何在画布中旋转形状,html5?

nop*_*ope 4 javascript html5 canvas

我试图用这个旋转一条线

window.onload= function(){
        var canvas=document.getElementById("foo");
        var context=canvas.getContext("2d");

        context.moveTo(250, 50);
        context.lineTo(250, 250);
        context.stroke();
        context.rotate(0.30);

    };
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我想我错过了一些步骤.谁有人解释一下?

小智 26

rotate()实际上旋转了整个坐标系.默认为0,0(画布的左上角).你需要按照这些方针做点什么:

context.save(); // saves the coordinate system
context.translate(250,50); // now the position (0,0) is found at (250,50)
context.rotate(0.30); // rotate around the start point of your line
context.moveTo(0,0) // this will actually be (250,50) in relation to the upper left corner
context.lineTo(0,200) // (250,250)
context.stroke();
context.restore(); // restores the coordinate system back to (0,0)
Run Code Online (Sandbox Code Playgroud)

查看此链接以获得有关translate()和rotate()如何工作的非常好的解释: tutsplus tutorial

史蒂夫


c-s*_*ile 6

请改用:

context.rotate(0.30); // <<< set current transformation to rotated
context.moveTo(250, 50);
context.lineTo(250, 250);
context.stroke();
Run Code Online (Sandbox Code Playgroud)

  • 当然,当你调用笔划时它会立即绘制线条,当调用旋转函数时,线条已被绘制,因此,它不会受到旋转的影响,所以你以前就这样做了. (3认同)