canvas变换

时间:2023-03-09 18:43:51
canvas变换

canvas变换

  1. 方法

    save()                  保存canvas状态
    restore() 回复canvas保存的状态
    translate(x, y) 移动canvas位置
    rotate(radians) 顺时针方向旋转canvas,弧度 = (Math.PI/180)*角度)
    scale(x, y) 缩放坐标轴,如果是负数则坐标轴反向
  2. 移动画布

    canvas变换

    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);
  3. 旋转画布

    canvas变换

    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);
    }
  4. 缩放坐标轴

    canvas变换

    ctx.fillStyle='orange';
    ctx.font = '30px serif';
    ctx.translate(200, 100);
    ctx.scale(-1, 1);
    ctx.fillText('Hello world', 10, 50);