javascript 如何在 canvas,html5 中旋转形状?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5998924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:05:26  来源:igfitidea点击:

how can i rotate a shape in canvas,html5?

javascripthtmlcanvas

提问by nope

im tried to rotate a line with this

我试图用这个旋转一条线

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);

    };

what am i doing wrong? i think im missing some steps. can anyone explain?

我究竟做错了什么?我想我错过了一些步骤。谁能解释一下?

回答by Steve

the rotate() actually rotates the entire coordinate system. Which defaults to 0,0 (Upper left corner of your canvas). You'd need to do something along these lines:

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)

Check out this link for a really good explanation of how translate() and rotate() work: tutsplus tutorial

查看此链接以获得对 translate() 和 rotate() 如何工作的很好的解释: tutsplus 教程

Steve

史蒂夫

回答by c-smile

Use this instead:

改用这个:

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

回答by Reiniel Tredes

context.rotate((Math.PI / 180) * 25); //Rotate the canvas by 25 degrees

context.save();
context.beginPath();
context.rotate((Math.PI / 180) * 25); //Rotate the canvas by 25 degrees
context.moveTo(250, 50);
context.lineTo(250, 250);
context.stroke();
context.closePath();
context.restore(); // to reset the canvas rotation