裁剪画布/导出具有一定宽度和高度的HTML5画布

为此,创建一个临时画布以在当前画布上进行绘制。之后,在临时画布上使用toDataUrl()方法-

var c = document.getElementsByTagName("canvas");
var ctx = c[0].getContext("2d");
var data = ctx.getImageData(0, 0, c[0].width, c[0].height);
var compositeOperation = ctx.globalCompositeOperation;

ctx.globalCompositeOperation = "destination-over";
ctx.fillStyle = "#800000";
ctx.fillRect(0,0,c[0].width,c[0].height);

var tempCanvas = document.createElement("canvas"),
tCtx = tempCanvas.getContext("2d");
tempCanvas.width = 550;
tempCanvas.height = 280;
tCtx.drawImage(canvas[0],0,0);