缩放HTML Canvas元素

时间:2014-09-08 03:43:02

标签: javascript html canvas scale

在我的主项目中,我有很多小的画布元素(想想:精灵地图中的精灵),我需要能够在将它们绘制到主画布之前缩放它们。这是我的基本代码:

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;

var miniCanvas = document.createElement('canvas');
var miniCanvasContext = miniCanvas.getContext('2d');

miniCanvasContext.beginPath();
miniCanvasContext.rect(0,0,100,100);
miniCanvasContext.closePath();
miniCanvasContext.fillStyle = 'red';
miniCanvasContext.fill();

miniCanvasContext.scale(2,2);//THIS IS THE PROBLEM


ctx.drawImage(miniCanvas, 100, 100);

这个测试在jsfiddle上进行:JSFIDDLE

基本上,我需要将这个红色方块的大小增加两倍。

感谢。

1 个答案:

答案 0 :(得分:1)

drawImage方法有一个允许你用缩放绘制miniCanvas的版本:

// the last 2 parameters are scaled Width & scaled Height

// parameters:
// 1st: the image source
// 2nd,3rd: the upper-left part of the source to clip from
// 4th,5th: the width & height to clip from the source
// 6th,7th: the upper-left part of the canvas to draw the clipped image
// 8th,9th: the scaled width & height to draw on the canvas

ctx.drawImage(miniCanvas, 0,0,100,100, 0,0,200, 200);