HTML5如何添加图片遮罩,带有HTML5画布的putImageData的遮罩?
我想從現(xiàn)有的圖像中采取不規(guī)則形狀的部分,并使用HTML5畫布將其呈現(xiàn)為Javascript中的新圖像。因此,只有多邊形邊界內(nèi)的數(shù)據(jù)才會(huì)被復(fù)制。我提出的方法包括:帶有HTML5畫布的putImageData的遮罩?
在新畫布中繪制多邊形。
創(chuàng)建使用getImageData(矩形)
應(yīng)用數(shù)據(jù)到新的畫布使用從原來(lái)的帆布clip
將數(shù)據(jù)復(fù)制使用putImageData
口罩它沒(méi)有工作,整個(gè)矩形(例如來(lái)自邊界外的來(lái)源的東西)仍然出現(xiàn)。 This question解釋了原因: “規(guī)范說(shuō)明putImageData不會(huì)受到剪輯區(qū)域的影響。”黨!
我也嘗試?yán)L制形狀,設(shè)置context.globalCompositeOperation = "source-in",然后使用putImageData。同樣的結(jié)果:沒(méi)有應(yīng)用掩膜。我懷疑是出于類似的原因。
關(guān)于如何完成此目標(biāo)的任何建議?以下是我正在進(jìn)行的工作的基本代碼,以防不清楚我正在嘗試做什么。 (不要試圖太難調(diào)試它,它會(huì)從使用很多不在這里的函數(shù)的代碼中清理/提取,只是試圖顯示邏輯)。
// 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();
總結(jié)
以上是生活随笔為你收集整理的HTML5如何添加图片遮罩,带有HTML5画布的putImageData的遮罩?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 解说redis中如何实现高可用
- 下一篇: 从事前端开发必须要了解的CSS原理(转)