canvas变换

canvas变换

canvas变换

  1. 方法

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

    1108804-20190210193825428-1799724078.png

    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变换_第1张图片

    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. 缩放坐标轴

    1108804-20190210195137617-1361677644.png

    ctx.fillStyle='orange';
    ctx.font = '30px serif';
    ctx.translate(200, 100);
    ctx.scale(-1, 1);
    ctx.fillText('Hello world', 10, 50);
posted @ 2019-02-10 19:54 qz奔跑的马 阅读( ...) 评论( ...) 编辑 收藏

你可能感兴趣的:(canvas变换)