Canvas rotate方法详解,掌握旋转变换原理、绕点旋转技巧和实际应用案例。rotate方法用于旋转坐标系,是实现图形旋转效果的核心方法。
ctx.rotate(angle)
| 参数 | 类型 | 说明 |
|---|---|---|
| angle | number | 旋转角度(弧度),正数顺时针,负数逆时针 |
rotate方法围绕当前坐标系原点旋转整个坐标系:
// 围绕原点(0, 0)旋转45度
ctx.rotate(Math.PI / 4)
ctx.fillRect(0, 0, 100, 50)
Canvas使用弧度制,常用转换:
// 角度转弧度
const radians = degrees * Math.PI / 180
// 弧度转角度
const degrees = radians * 180 / Math.PI
// 常用角度
const ANGLES = {
30: Math.PI / 6,
45: Math.PI / 4,
60: Math.PI / 3,
90: Math.PI / 2,
120: 2 * Math.PI / 3,
180: Math.PI,
270: 3 * Math.PI / 2,
360: 2 * Math.PI
}
rotate调用是累积的:
ctx.rotate(Math.PI / 6) // 旋转30度
ctx.rotate(Math.PI / 6) // 再旋转30度,总共60度
// 等价于
ctx.rotate(Math.PI / 3) // 直接旋转60度
rotate只能绕原点旋转,要绕任意点旋转需要配合translate:
function rotateAroundPoint(ctx, x, y, angle) {
ctx.translate(x, y)
ctx.rotate(angle)
ctx.translate(-x, -y)
}
// 使用示例
ctx.save()
rotateAroundPoint(ctx, 100, 100, Math.PI / 4)
ctx.fillRect(75, 75, 50, 50)
ctx.restore()
结合requestAnimationFrame实现旋转动画:
let angle = 0
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.save()
ctx.translate(centerX, centerY)
ctx.rotate(angle)
ctx.fillRect(-25, -25, 50, 50)
ctx.restore()
angle += 0.02
requestAnimationFrame(animate)
}
animate()
// 顺时针旋转45度
ctx.rotate(Math.PI / 4)
// 逆时针旋转45度
ctx.rotate(-Math.PI / 4)
旋转中心
rotate始终围绕原点旋转,要绕其他点旋转需配合translate。
角度单位
Canvas使用弧度,不是角度,注意转换。
累积效应
多次rotate会累积,使用save/restore或setTransform重置。
坐标系变化
旋转后坐标系的方向改变,后续绑制都会受影响。