2012-03-06 21 views
1

我嘗試創建一個腳本,改變圖像的色彩,我找到了一種方法來改變顏色,但因爲圖像有一個白色的背景,改變了所有的形象,是可以忽略的白色像素不知何故?畫布中的白色像素是透明的嗎?

這是迄今爲止代碼:

<!doctype html> 
<html> 
<head> 

</head> 

<body> 
<h4>Original Image</h4> 
<img id="testImage" src='../src/test.png'/> 

<h4>Image copied to canvas</h4> 
<canvas id="canvas" width="500" height="500"></canvas> 

<h4>Modified Image copied to an image tag</h4> 
<img id="imageData"/> 

<script> 

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

ctx.drawImage(image,0,0); 

var imgd = ctx.getImageData(0, 0, 128, 128), 
    pix = imgd.data, 
    uniqueColor = [0,0,150]; // Blue for an example, can change this value to be anything. 

// Loops through all of the pixels and modifies the components. 
for (var i = 0, n = pix.length; i <n; i += 4) { 
     pix[i] = uniqueColor[0]; // Red component 
     pix[i+1] = uniqueColor[1]; // Blue component 
     pix[i+2] = uniqueColor[2]; // Green component 
     //pix[i+3] is the transparency. 
} 

ctx.putImageData(imgd, 0, 0); 


var savedImageData = document.getElementById("imageData"); 
savedImageData.src = canvas.toDataURL("image/png"); 
</script> 
</body> 
</html> 
+0

您將要使用@aglassman的答案。但是爲圖像製作一個畫布元素並在啓動時處理它。然後將畫布元素繪製到畫布上。這將顯着提高性能。 – 2012-03-06 18:59:27

回答

2

將這樣的事情對你的工作?

if (pix[i] == 255 && 
     pix[i+1] == 255 && 
     pix[i+2] == 255) 
    { 
    //pixel is white 
    } 
    else 
    { 
    //pixel is not white, modify it. 
    } 
+0

我試圖得到那個工作,似乎沒有這樣的伎倆壽(我可能是把它放在錯誤的IM沒有專家) 我將如何把這段代碼? – justanotherhobbyist 2012-03-06 19:25:03

+0

對不起,現在你的代碼,它的工作原理。你真棒謝謝你。 – justanotherhobbyist 2012-03-06 19:29:29

+0

它適用於某些圖像,其他人不會,很奇怪。似乎不工作,當我從網絡上獲取圖像。 – justanotherhobbyist 2012-03-06 19:35:13