有數百個教程,如何通過drawImage()在畫布上裁剪圖像。裁剪畫布/導出具有一定寬度和高度的html5畫布
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:我不想調整大小或規模,只是裁剪/裁剪到固定窗口。 Here我讀到,你只能指定canvas.width和canvas.height - 但是這會清除畫布。
太棒了,效果非常好! /唯一令我感到不快的是,當圖像已經顯示時,Firefox顯示加載頁面(標籤顯示轉彎圓圈)。點擊ESC在URL中顯示wyciwyg://!! ...「wyciwyg是一個內部的URI方案,用於表示document.write結果頁面」/但無論如何,很高興你給了我一個工作解決方案! –
「data」變量已分配但從未使用過...... –
也不是compositeOperation變量 –