scale(x,y): 第一个参数是 X 轴的缩放值,第二个参数是 Y 轴的缩放值。
- function cxt_scale() {
- var ctx = document.getElementById("trascanvas2").getContext("2d");
- ctx.fillStyle="#666";
- ctx.fillRect(0,0,100,100);
- ctx.fillStyle="#693";
- ctx.scale(2,2);
- ctx.globalCompositeOperation ="destination-atop";//合成
- ctx.fillRect(0,0,100,100);
- };
图中灰色的图是正常大小,绿色的是经过 scale 放大的。
注意:代码中 globalCompositeOperation 这个 api 是用来处理两个图之间的合成关系的。
context.transform(,,,,,):
context.setTransform(,,,,,):
a: 水平缩放,b:水平倾斜,c:垂直倾斜,d:垂直缩放,e:水平位移,f:垂直移动
当图经过了很多次变换之后,我们可以在变换的前后使用 save()&restore() 来保存状态,或者直接在变换前使用 setTransform(1,0,0,1,0,0) 来重置画布。
- function cxt_transform() {
- var ctx = document.getElementById("trascanvas3").getContext("2d");
- ctx.save();
- ctx.fillStyle="yellow";
- ctx.fillRect(0,0,250,100)
- ctx.setTransform(1,0.5,-0.5,1,30,10);
- ctx.fillStyle="red";
- ctx.fillRect(0,0,250,100);
- ctx.transform(1,0.5,-0.5,1,30,10);
- ctx.fillStyle="blue";
- ctx.fillRect(0,0,250,100);
- ctx.restore();
- //ctx.setTransform(1,0,0,1,0,0);
- ctx.fillStyle="yellow";
- ctx.translate(300,0);
- ctx.fillRect(0,0,250,100);
- };
可以看到,最后一个黄色矩形按照正常的方式显示在(300,0)的位置。蓝色矩形则是在红色矩形的基础上变化。我们把上图的红色代码换成:ctx.setTransform(1,0.5,-0.5,1,30,10);
可以看到结果如下:
由于在蓝色部分重置了变换矩阵,重新构建了矩阵,所以红色矩型被蓝色矩形遮盖了。
所以我们看到 setTransform() 和 transform 之间的差别就是,前者会重置上次变换然后重新构建新的变换矩阵,而后者直接在上次的变换基础上构建新的变换。
来源: