html5 更新图片颜色示例代码_html5教程技巧
2015-01-04 13:08:39
[小 大]
已经帮助:人解决问题
本文为为大家介绍了html5 更新图片颜色的具体实现,喜欢的朋友可以练练手
8awHTML5中文学习网 - HTML5先行者学习网
<canvas id="c1" width="1220" height = "880" style="background: none repeat scroll 0% 0% transparent; "></canvas> 8awHTML5中文学习网 - HTML5先行者学习网
<script> 8awHTML5中文学习网 - HTML5先行者学习网
var cID = "c1"; 8awHTML5中文学习网 - HTML5先行者学习网
var image = new Image(); 8awHTML5中文学习网 - HTML5先行者学习网
image.src = "Eye/item_eye_1.png"; 8awHTML5中文学习网 - HTML5先行者学习网
image.onload = function () { 8awHTML5中文学习网 - HTML5先行者学习网
recolorImage(cID,image, 0, 0, 0, 255, 0, 0); 8awHTML5中文学习网 - HTML5先行者学习网
} 8awHTML5中文学习网 - HTML5先行者学习网
function recolorImage(c,img, oldRed, oldGreen, oldBlue, newRed, newGreen, newBlue) { 8awHTML5中文学习网 - HTML5先行者学习网
var c = document.getElementById(c); 8awHTML5中文学习网 - HTML5先行者学习网
var ctx = c.getContext("2d"); 8awHTML5中文学习网 - HTML5先行者学习网
var w = img.width; 8awHTML5中文学习网 - HTML5先行者学习网
var h = img.height; 8awHTML5中文学习网 - HTML5先行者学习网
c.width = w; 8awHTML5中文学习网 - HTML5先行者学习网
c.height = h; 8awHTML5中文学习网 - HTML5先行者学习网
// draw the image on the temporary canvas 8awHTML5中文学习网 - HTML5先行者学习网
ctx.drawImage(img, 0, 0, w, h); 8awHTML5中文学习网 - HTML5先行者学习网
// pull the entire image into an array of pixel data 8awHTML5中文学习网 - HTML5先行者学习网
var imageData = ctx.getImageData(0, 0, w, h); 8awHTML5中文学习网 - HTML5先行者学习网
// examine every pixel, 8awHTML5中文学习网 - HTML5先行者学习网
// change any old rgb to the new-rgb 8awHTML5中文学习网 - HTML5先行者学习网
for (var i = 0; i < imageData.data.length; i += 4) { 8awHTML5中文学习网 - HTML5先行者学习网
// is this pixel the old rgb? 8awHTML5中文学习网 - HTML5先行者学习网
if (imageData.data[i] == oldRed && imageData.data[i + 1] == oldGreen && imageData.data[i + 2] == oldBlue) { 8awHTML5中文学习网 - HTML5先行者学习网
// change to your new rgb 8awHTML5中文学习网 - HTML5先行者学习网
imageData.data[i] = newRed; 8awHTML5中文学习网 - HTML5先行者学习网
imageData.data[i + 1] = newGreen; 8awHTML5中文学习网 - HTML5先行者学习网
imageData.data[i + 2] = newBlue; 8awHTML5中文学习网 - HTML5先行者学习网
} 8awHTML5中文学习网 - HTML5先行者学习网
} 8awHTML5中文学习网 - HTML5先行者学习网
// put the altered data back on the canvas 8awHTML5中文学习网 - HTML5先行者学习网
ctx.putImageData(imageData, 0, 0); 8awHTML5中文学习网 - HTML5先行者学习网
} 8awHTML5中文学习网 - HTML5先行者学习网
</script> 8awHTML5中文学习网 - HTML5先行者学习网