我想從現有的圖像中採取不規則形狀的部分,並使用HTML5畫布將其呈現爲Javascript中的新圖像。因此,只有多邊形邊界內的數據纔會被複制。我提出的方法包括:帶有HTML5畫布的putImageData的遮罩?
- 在新畫布中繪製多邊形。
- 創建使用
getImageData
(矩形) - 應用數據到新的畫布使用從原來的帆布
clip
- 將數據複製使用
putImageData
口罩它沒有工作,整個矩形(例如來自邊界外的來源的東西)仍然出現。 This question解釋了原因: 「規範說明putImageData
不會受到剪輯區域的影響。」黨!
我也嘗試繪製形狀,設置context.globalCompositeOperation = "source-in"
,然後使用putImageData
。同樣的結果:沒有應用掩膜。我懷疑是出於類似的原因。
關於如何完成此目標的任何建議?以下是我正在進行的工作的基本代碼,以防不清楚我正在嘗試做什麼。 (不要試圖太難調試它,它會從使用很多不在這裏的函數的代碼中清理/提取,只是試圖顯示邏輯)。
// coords is the polygon data for the area I want
context = $('canvas')[0].getContext("2d");
context.save();
context.beginPath();
context.moveTo(coords[0], coords[1]);
for (i = 2; i < coords.length; i += 2) {
context.lineTo(coords[i], coords[i + 1]);
}
//context.closePath();
context.clip();
$img = $('#main_image');
copy_canvas = new_canvas($img); // just creates a new canvas matching dimensions of image
copy_ctx = copy.getContext("2d");
tempImage = new Image();
tempImage.src = $img.attr("src");
copy_ctx.drawImage(tempImage,0,0,tempImage.width,tempImage.height);
// returns array x,y,x,y with t/l and b/r corners for a polygon
corners = get_corners(coords)
var data = copy_ctx.getImageData(corners[0],corners[1],corners[2],corners[3]);
//context.globalCompositeOperation = "source-in";
context.putImageData(data,0,0);
context.restore();
真棒!有用!非常感謝。 – 2011-05-09 21:12:13
哦,快速的問題 - 你可以想出一種方法來做到這一點,沒有三個溫度。畫布?我有1加載一個主圖像的副本,然後一個複製矩形,第三個有面具,我應用第二。我感覺好像我一定在某個地方做得太多了,但我想不出從完整圖像直接轉到只包含矩形的畫布。 – 2011-05-09 21:15:25
在我包含的代碼中,您可以構建一個Composite,它可以根據需要製作儘可能多的畫布列表,但是,我建議您在性能的角度謹慎操作。所以測試和嘗試是一個很好的做法;) – 2011-05-09 21:48:27