简体   繁体   English

如何旋转画布上下文

[英]How to Rotate Canvas Context

How can I rotate a canvas object like - 如何旋转画布对象,例如-

ctx.beginPath();
ctx.fillStyle = 'rgba(52, 52, 53, 0.75)';
ctx.fillRect(50, 50, 100, 100);

It doesn't need to be a loop, but how can I rotate this? 它不必是循环,但如何旋转它呢?

Like this: 像这样:

<html>
<body>
<canvas id="myCanvas" width="134px" height="331px" onclick="draw()"></canvas> 
<script>
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    ctx.fillStyle = 'rgba(52, 52, 53, 0.75)';
    ctx.rotate(20*Math.PI/180);
    ctx.fillRect(50, 50, 100, 100);
</script>
</body>
</html>

@M. @M。 Page's answer does cause this to rotate, but not in the way you are probably thinking. Page的答案的确会导致这种情况旋转,但不会以您可能认为的方式发生。 In general rotate() is not about the middle point of your object, but another point (0,0) . 通常rotate()不在对象的中间,而是在另一点(0,0) To fix this we need to make our object's middle point to (0,0) , then do a rotation, then translate back. 为了解决这个问题,我们需要将对象的中间点设为(0,0) ,然后进行旋转,然后平移回去。 Like so: 像这样:

ctx.translate((c.width/2) - 50, (c.height/2) - 50); // move back
ctx.rotate(20*Math.PI/180); // rotate
ctx.translate((-c.width/2) + 50, (-c.height/2) + 50); // move to 0,0
ctx.fillRect(50, 50, 100, 100); // Notice the middle point would be (x+50, y+50)

Notice that this is actually done from the bottom-up, which is how the stack for graphics work. 注意,这实际上是自下而上完成的,这是图形堆栈的工作方式。

Here is an example , notice the difference if you comment the translate() out. 这是一个示例 ,如果您注释了translate() ,请注意不同之处。

The -50 and +50 comes from placing the center of our box in the middle. -50+50来自将盒子的中心放在中间。 Without them it will rotate about the bottom-right corner of the box and not the center of the box. 没有它们,它将绕盒子的右下角而不是盒子的中心旋转。 To give a visual example: 给出一个直观的例子:

Basically we want to translate to the position where our box's mid-point is at (0,0) . 基本上,我们想转换到盒子的中点在(0,0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM