1、translate:translate() 方法重新映射画布上的 (0,0) 位置。
注:当在 translate() 之后调用诸如 fillRect() 之类的方法时,值会添加到 x 和 y 坐标值上。
多个translate()的值会叠加。在 下例中,四个矩形的绘制顺序为:红-->蓝-->紫-->黄,绘制完成后,最后的坐标原点会位于黄色矩形的左上顶点处。
1 canvas.width = 400 2 canvas.height = 300 3 4 context.fillStyle = '#FF4444' 5 context.fillRect(0,0,200,150) 6 7 context.beginPath() 8 context.translate(200,150) 9 context.fillStyle = '#005588' 10 context.fillRect(0,0,200,150) 11 12 context.beginPath() 13 context.translate(0,-150) 14 context.fillStyle = '#AA66CC' 15 context.fillRect(0,0,200,150) 16 17 context.beginPath() 18 context.translate(-200,150) 19 context.fillStyle = '#FF8800' 20 context.fillRect(0,0,200,150)
2、rotate:rotate() 方法旋转当前的绘图。
旋转角度单位为弧度。角度转换弧度公式:θ*Math.PI/180
1 context.fillStyle = '#FF4444' 2 context.fillRect(100,50,200,150) 3 4 context.translate(100,50) 5 context.rotate(30*Math.PI/180) 6 context.fillStyle = '#005588' 7 context.fillRect(0,0,200,150)
3、scale:scale() 方法缩放当前绘图至更大或更小。
注:scale() 方法会对所有绘图状态进行缩放,包括线宽、距离等等
1 context.lineWidth = 2 2 context.strokeStyle = '#FF4444' 3 context.strokeRect(5,5,50,50) 4 5 const COLOR = ['#005588','#AA66CC','#FF8800'] 6 7 for(let color of COLOR){ 8 context.scale(2,2) 9 context.strokeStyle = color 10 context.strokeRect(5,5,50,50) 11 }
由上面的几个例子可以得出结论:canvas的图形变换都是基于坐标系的变换,每一次变换都会改变当前绘图环境的坐标系统。
4、save 以及 restore :
save()----保存当前环境的状态。
restore()----返回之前保存过的路径状态和属性。
由于图形变换会改变当前绘图环境的坐标系统,在绘制复杂图形时难免就会遇到这种情况:我们希望在一系列图形变换之后,继续在之前某一个状态下的坐标系统之上来进行绘图。
那么就势必需要将已经产生的变换再转换回之前的状态,比如translate(100,100)之后就需要translate(-100,-100)。如果绘制的图形较为复杂,那么代码量必然暴增。因此就需要用到save()和restore()。
1 context.fillStyle = '#FF4444' 2 context.fillRect(0,0,200,150) 3 context.save() 4 5 const COLORS = ['#005588','#AA66CC','#FF8800'] 6 let num = -1; 7 for(let i = 0;i<COLORS.length;i++){ 8 num*=-1 9 context.translate(200*(1-i),150*num) 10 context.fillStyle = COLORS[i] 11 context.fillRect(0,0,200,150) 12 } 13 14 context.restore() 15 context.fillStyle = '#169FE6' 16 context.translate(100,75) 17 context.fillRect(0,0,200,150)
5、transform:定义一个变换矩阵
a c e
b d f
0 0 1
a----水平缩放绘图。
b----水平倾斜绘图。
c----垂直倾斜绘图。
d----垂直缩放绘图。
e----水平移动绘图。
f----垂直移动绘图。
1 context.fillStyle = '#FF4444' 2 context.fillRect(0,0,200,150) 3 4 context.fillStyle = '#169FE6' 5 context.transform(1,0.5,-0.5,1,30,10); 6 context.fillRect(0,0,200,150) 7 8 context.transform(1,0.5,-0.5,1,30,10); 9 context.fillStyle="#AA66CC"; 10 context.fillRect(0,0,250,100);
6、setTransform:setTransform() 方法把当前的变换矩阵重置为单位矩阵,然后以相同的参数运行 transform()。
1 context.fillStyle = '#FF4444' 2 context.fillRect(0,0,200,150) 3 4 context.fillStyle = '#169FE6' 5 context.setTransform(1,0.5,-0.5,1,30,10); 6 context.fillRect(0,0,200,150) 7 8 context.setTransform(1,0.5,-0.5,1,30,10); 9 context.fillStyle="#AA66CC"; 10 context.fillRect(0,0,250,100);