Canvas API中提供的变形方法主要有:
CanvasRenderingContext2D.scale(x, y)
CanvasRenderingContext2D.rotate(angle)
CanvasRenderingContext2D.translate(x, y)
CanvasRenderingContext2D.transform(a, b, c, d, e, f)
CanvasRenderingContext2D.setTransform(a, b, c, d, e, f)
在绘制图片一节示例中我们使用GridFunny提供的clone方法实现类似缩放的效果,下面使用scale方法再次实现缩放:
// 分别为GridFunny添加scale、rotate、translate、transform方法 var grid = new GridFunny({ gridColor: "green", canvasClassName: "transform-canvas", nextDraw: function() { var context = this.context, x = this.pixelX + 50, y = this.pixelY + 10, w = 240, h = 50; context.fillStyle = '#ccc'; context.strokeStyle = 'red'; context.font = '30px Arial'; context.fillRect(x, y, w, h); context.strokeText("transform canvas", x + 5, 85); } }); grid.start(); // scale grid.scale({ width: 300, height: 300 }, function(canvas) { canvas.className = grid.settings.canvasClassName; grid.settings.container.appendChild(canvas); }); // rotate grid.rotate({ angle: 30 * Math.PI / 180 }, function(canvas) { canvas.className = grid.settings.canvasClassName; grid.settings.container.appendChild(canvas); }); // translate grid.translate({ x: 120, y: 50 }, function(canvas) { canvas.className = grid.settings.canvasClassName; grid.settings.container.appendChild(canvas); }); // transform grid.transform({ a: 0.5, b: 0.4, c: -0.2, d: 1.2, e: 200, f: 0 }, function(canvas) { canvas.className = grid.settings.canvasClassName; grid.settings.container.appendChild(canvas); });
rotate、translate、transform方法会对canvas进行不同程度的选择,如果是原始尺寸操作的话,有部分不能完全显示,这时需要配合scale对原始canvas进行缩放,以便显示全图。