绘制正方形并旋转它? [英] draw square and rotate it?
问题描述
这怎么不工作?只旋转只与图像一起工作?
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();
c $ c> context.rotate ,因为轴点默认在坐标(0,0),你的方块有时会被绘制出边界。
通过将旋转点移动到正方形的中间,您可以成功旋转它。
注意:确保在绘制正方形之前轮换画布。
//枢轴点坐标=正方形的中心
var cx = 130; //(60 + 200)/ 2
var cy = 130; //(60 + 200)/ 2
//请注意,方形
//的x和y值是相对于枢轴点的。
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();
说明:
$ b b
-
context.save();
保存坐标系的当前状态。
-
context.translate(cx,cy);
移动轴点。 -
context.rotate(deg * Math.PI / 180);
将正方形旋转到deg
(请注意,参数以弧度表示,而不是度数) -
context.fillRect(x,y,w,h) / code>绘制正方形
-
context.restore
这里是 JS Fiddle示例。
这是另一个 JS Fiddle示例,其中包含HTML5滑块。
how come this doesn't work? does rotate only work with images?
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();
You are rotating the whole canvas when you use context.rotate
, and since the pivot point is defaulted at the coordinates (0, 0), your square sometimes will be drawn out of bounds.
By moving the pivot point to the middle of the square, you can then rotate it successfully.
Note: Make sure you rotate the canvas before you draw the square.
// 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();
Explanation:
context.save();
saves the current state of the coordinate system.context.translate(cx, cy);
moves the pivot point.context.rotate(deg * Math.PI/180);
rotates the square todeg
degrees (Note that the parameter is in radians, not degrees)context.fillRect( x, y, w, h );
draws the squarecontext.restore();
restores the last state of the coordinate system.
Here is a JS Fiddle example.
Here is another JS Fiddle example that features a HTML5 slider.
这篇关于绘制正方形并旋转它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!