canvas变换
-
方法
save() 保存canvas状态
restore() 回复canvas保存的状态
translate(x, y) 移动canvas位置
rotate(radians) 顺时针方向旋转canvas,弧度 = (Math.PI/180)*角度)
scale(x, y) 缩放坐标轴,如果是负数则坐标轴反向 -
移动画布
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d'); ctx.save();
ctx.fillStyle='orange';
ctx.translate(10, 10);
ctx.fillRect(0,0, 10, 10)
ctx.restore(); ctx.save();
ctx.fillStyle='red';
ctx.translate(20, 20);
ctx.fillRect(0,0, 10, 10);
ctx.restore(); ctx.save();
ctx.fillStyle='blue';
ctx.translate(30, 30);
ctx.fillRect(0,0, 10, 10);
ctx.restore(); ctx.save();
ctx.fillStyle='green';
ctx.translate(40, 40);
ctx.fillRect(0,0, 10, 10); -
旋转画布
ctx.fillStyle='orange';
ctx.translate(200, 200); for(var i = 1; i <= 18; i++){
ctx.rotate((Math.PI / 180) * 20 * i);
ctx.fillRect(0, 0, 100, 100);
} -
缩放坐标轴
ctx.fillStyle='orange';
ctx.font = '30px serif';
ctx.translate(200, 100);
ctx.scale(-1, 1);
ctx.fillText('Hello world', 10, 50);