(四)旋转 缩放 位移 保存状态

旋转

rotate(10) //围绕原点旋转

    var canvas = document.getElementById("canvas");
    if(canvas.getContext){
        var ctx = canvas.getContext("2d");
        ctx.beginPath();
        ctx.translate(200,200);
        ctx.arc(0,0,100,0,2*Math.PI,false);
        ctx.moveTo(94,0);
        ctx.arc(0,0,94,0,2*Math.PI,false);
        ctx.moveTo(0,0);
        ctx.lineTo(0,-90);
        
        //围绕圆点旋转
        ctx.rotate(10);
        
        ctx.moveTo(0,0);
        ctx.lineTo(-90,0);

        ctx.stroke();
        ctx.closePath();
    }

缩放

scale(2,2)  //在原图形的基础上 *2  x 周对应第一个参数 y轴对应第二个参数

var canvas = document.getElementById("canvas");
    if(canvas.getContext){
        var ctx = canvas.getContext("2d");

        ctx.beginPath();

        ctx.translate(100,100);//位移
        ctx.rotate(0.5);//旋转
        ctx.scale(1.5,1.2)//围绕圆点缩放x轴1.5倍,y轴1.2倍

        ctx.fillStyle = "blue";
        ctx.fillRect(0,0,200,100);
        ctx.stroke();
        ctx.closePath();
    }

位移

translate(x,y)  //把原点移动到xy的地方

var canvas = document.getElementById('canvas');
    if(canvas.getContext){
        var ctx = canvas.getContext("2d");
        ctx.beginPath();
        ctx.translate(200,200);//移动圆点到 200,200 的位置

        ctx.arc(0,0,100,0,2*Math.PI,false);

        ctx.moveTo(94,0);
        ctx.arc(0,0,94,0,2*Math.PI,false);

        ctx.moveTo(0,0);
        ctx.lineTo(0,-90);
        ctx.moveTo(0,0);
        ctx.lineTo(-80,0);
ctx.stroke(); ctx.closePath(); }

保存状态

save()  //调用这个方法会把所有设置都保存到一个栈结构里,不影响下文,可以多次一级一级保存

restore()  //调用这个方法会恢复相对应save()方法保存的设置,可以多次一级一级恢复

var canvas = document.getElementById("canvas");
    if(canvas.getContext){
        var ctx = canvas.getContext("2d");
        ctx.beginPath();
        
        ctx.fillStyle = "red";
        ctx.save();//保存红色 一级
        
        ctx.fillStyle = "green";
        ctx.save();//保存绿色 二级
        
        ctx.restore();//恢复绿色 二级
        ctx.fillRect(50,50,100,50); //绿色
        
        ctx.restore();//恢复红色 一级
        ctx.fillRect(100,100,100,50);//红色
        
        ctx.stroke();
        ctx.closePath();
    }
原文地址:https://www.cnblogs.com/chefweb/p/6046458.html