AS in subject。我想旋转一个物体,但我不希望它将它移动到任何地方,只需旋转它并将其保留在原位。函数绘制只绘制矩形。
<!DOCTYPE html>
<html>
<head>
<script>
var ctx, canvas;
window.onload = function(){
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
//sciana
draw();
}
function draw() {
//ctx.scale(0.5,0.5);
ctx.rotate(Math.PI /6);//here I rotate but it moves...
ctx.fillRect( 100, 100, 50, 50);
}
</script>
</head>
<body>
<canvas id="myCanvas" width="600" height="600" style="background-color:#D0D0D0">
Twoja przeglądarka nie obsługuje elementu Canvas.
</canvas>
</body>
</html>
答案 0 :(得分:1)
Draw - with shape centered at 0,0
Rotate
Translate - to cx,cy , where cx,cy is the center of the shape, where it is to be located.
为了达到这个效果,你必须以完全相反的顺序对2D上下文进行函数调用,如下所示:
context.translate(cx, cy);
context.rotate (radians);
context.fillRect (x, y, width, height);
答案 1 :(得分:0)
只需使用CSS3的rotate
属性。
-webkit-transform: rotate(7.5deg);
-moz-transform: rotate(7.5deg);
-ms-transform: rotate(7.5deg);
-o-transform: rotate(7.5deg);
transform: rotate(7.5deg);
答案 2 :(得分:0)
画布上的旋转功能围绕原点旋转,以便围绕要转换到要绘制的形状中心的形状中心旋转,然后旋转,然后绘制形状。
您的最终代码可能如下所示:
<!DOCTYPE html>
<html>
<head>
<script>
var ctx, canvas;
window.onload = function(){
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
//sciana
draw();
}
function draw() {
//ctx.scale(0.5,0.5);
ctx.translate(125, 125);
ctx.rotate(Math.PI /6);//here I rotate but it moves...
ctx.fillRect(-25, -25, 50, 50);
}
</script>
</head>
<body>
<canvas id="myCanvas" width="600" height="600" style="background-color:#D0D0D0">
Twoja przegladarka nie obsluguje elementu Canvas.
</canvas>
</body>
</html>