在 HTML5 Canvas 中沿其轴旋转正方形?

use*_*294 3 html javascript rect html5-canvas

我想创建一个在其轴上旋转正方形的函数。

var halfWidth = canvas.width/2;
var halfHeight = canvas.height/2;

var x = halfWidth-10;
var y = halfHeight-10;
var w = 20;
var h = 20;
var deg = 45;

rotate(x, y, w, h, deg);

ctx.fillRect(x, y, w, h);
Run Code Online (Sandbox Code Playgroud)

功能:

function rotate(x, y, w, h, deg) {
    // ctx.translate() and ctx.rotate()
    // goes here.
}
Run Code Online (Sandbox Code Playgroud)

这该怎么做?

use*_*294 5

感谢Dr.dredel提供链接。

var cx = canvas.width/2;
var cy = canvas.height/2;

var x = -10;
var y = -10;
var w = 20;
var h = 20;
var deg = 45;

ctx.save();

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

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

ctx.restore();
Run Code Online (Sandbox Code Playgroud)

解释:

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

  • ctx.translate(cx, cy) 将原点更改为画布的中心

  • ctx.rotate(deg * Math.PI/180) 将正方形旋转 45 度(注意参数是弧度,不是度数)

  • ctx.fillRect( x, y, w, h ) 画正方形

  • ctx.restore() 恢复坐标系的最后状态。

JS小提琴链接

另一个 JS Fiddle 链接,带有 HTML5 滑块