有数百个教程,介绍如何在画布上通过 drawImage() 裁剪图像。
context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
但是,我有一个可以填充用户浏览器的画布。通过将画布导出为图像,我只想从 (0|0) 导出 640px*480px 的区域。
问题:我如何告诉 javascript 只使用 640*480 的画布作为 toDataURL()?
这是我到目前为止所拥有的:
$("#submitGraphic").click( function(){
var canvas = document.getElementsByTagName("canvas");
// canvas context
var context = canvas[0].getContext("2d");
// get the current ImageData for the canvas
var data = context.getImageData(0, 0, canvas[0].width, canvas[0].height);
// store the current globalCompositeOperation
var compositeOperation = context.globalCompositeOperation;
// set to draw behind current content
context.globalCompositeOperation = "destination-over";
//set background color
context.fillStyle = "#FFFFFF";
// draw background/rectangle on entire canvas
context.fillRect(0,0,canvas[0].width,canvas[0].height);
// not working, seems to clear the canvas? browser hangs?
// seems that I can click a white image in the background
/*canvas[0].width = 640;
canvas[0].height = 480;*/
// not working either
/*canvas[0].style.width = '640px';
canvas[0].style.height = '480px';*/
// not working at all
/*context.canvas.width = 640;
context.canvas.height = 480;*/
// write on screen
var img = canvas[0].toDataURL("image/png");
document.write('<a href="'+img+'"><img src="'+img+'"/></a>');
})
PS:我不想调整大小或缩放,只是剪裁/裁剪到固定窗口。在这里,我读到您只指定 canvas.width 和 canvas.height - 但这会清除画布。