2011-12-05 36 views

回答

7

畫布API有合成方法專門爲像「僅在不是在原始圖像中透明像素繪製」。這比處理圖像數據要容易得多。 (現在內嵌圖像)

帽尖到@ WilliamVanRensselaer的初始撥弄

jsFiddle示例

你想要的複合操作是source-in,這意味着「繪製我正在嘗試繪製的圖像的不透明部分,只有它們位於所繪圖像中不透明像素的頂部。」

HTML:

<a href="javascript:doIt()">paint non-transparent regions white</a><br> 
<canvas id="canvas" width="600" height="200"></canvas> 

的Javascript:

var canvas = document.getElementById("canvas"), 
    ctx = canvas.getContext("2d"); 

imgSrc = "http://d.pr/Td69+"; 
var b = document.getElementsByTagName("body")[0]; 
var i = document.createElement("img"); 
i.src = imgSrc; 
i.style.setProperty("display", "none"); 
i.onload = function() { 
    ctx.drawImage(i, 0, 0); 
} 
b.appendChild(i); 

window.doIt = function() { 
    ctx.globalCompositeOperation = "source-in"; 

    ctx.fillStyle = "#ffffff"; 
    ctx.fillRect(0, 0, 600, 200); 
} 

reference

+2

+1使用'globalCompositeOperation'而不是搞亂圖像數據。這應該比其他(完全正確的)解決方案快得多。 – Phrogz

+2

這是完美的,ellisbben! Phrogz提到的不僅速度更快,而且還避免了來源許可問題,這使得它更適用於各種情況。乾杯! –

0

這裏的東西,讓你開始。如果alpha不爲零,這基本上會將像素更改爲白色,但如果需要,可以進行修改。

示例:http://jsfiddle.net/Q27Qc/

var canvas = document.getElementById("canvas"), 
    ctx = canvas.getContext("2d"); 

// Put something on the canvas (can be an image) 
ctx.font = "100px Arial"; 
ctx.fillText("Google", 20, 130); 

// Get image data for part of the canvas (to see effects) 
var img = ctx.getImageData(20, 40, 80, 100), 
    imgData = img.data; 

// Loops through bytes and change pixel to white if alpha is not zero. 
for (var i = 0; i < imgData.length; i += 4) { 
    if (imgData[i + 3] !== 0) { 
     imgData[i] = 255; 
     imgData[i + 1] = 255; 
     imgData[i + 2] = 255; 
    } 
} 

// Draw the results 
ctx.putImageData(img, 20, 40); 
+0

沒有理由不成立,甚至完全透明的像素爲白色的RGB。 (應該測試看看跳過它們還是避免測試更快。)總之,除了@ellisben有更好的解決方案之外,我會給你+1。 – Phrogz