画平方并旋转它?

时间:2011-02-13 13:11:14

标签: html5 canvas rotation

为什么这不起作用?旋转只适用于图像吗?

            context.moveTo(60,60);
            context.lineTo(200,60);
            context.lineTo(200,200);
            context.lineTo(60,200);
            context.lineTo(60,60);


            context.stroke();
            context.rotate(45 * Math.PI / 180);
            context.restore();

1 个答案:

答案 0 :(得分:3)

当您使用context.rotate时,您正在旋转整个画布,并且由于枢轴点在坐标(0,0)处默认,因此您的方块有时会被绘制出边界。

通过将枢轴点移动到正方形的中间,您可以成功旋转它。

注意:确保在绘制正方形之前旋转画布。

// pivot point coordinates = the center of the square
var cx = 130; // (60+200)/2
var cy = 130; // (60+200)/2

// Note that the x and y values of the square 
// are relative to the pivot point.
var x = -70; // cx + x = 130 - 70 = 60
var y = -70; // cy + y = 130 - 70 = 60
var w = 140; // (cx + x) + w = 60 + w = 200
var h = 140; // (cy + y) + h = 60 + h = 200
var deg = 45;

context.save();

context.translate(cx, cy);
context.rotate(deg * Math.PI/180);

context.fillRect(x, y, w, h);

context.restore();


说明:

  • context.save();保存坐标系的当前状态。

  • context.translate(cx, cy);移动轴心点。

  • context.rotate(deg * Math.PI/180);将方块旋转到deg度(注意参数是弧度,而不是度数)

  • context.fillRect( x, y, w, h );绘制正方形

  • context.restore();恢复坐标系的最后一个状态。

这是JS Fiddle example

这是另一个JS Fiddle example that features a HTML5 slider

相关问题