我想用Javascript在一组图像中用透明的颜色替换紫色。我正在使用drawImage,getImageData和putImageData:我错了(在这里看到JsFIddle:http://jsfiddle.net/2pGfX/)?
HTML:
<img onclick="scegli(this.id)" id="c0">
<img onclick="scegli(this.id)" id="c1">
<img onclick="scegli(this.id)" id="c2">
<img onclick="scegli(this.id)" id="c3">
<canvas id="myCanvas"></canvas>
使用Javascript:
var items = ["image1.gif", "image2.gif", "image3.gif"];
var arraioParti = [
["a",0, 100, 100, 181, 43],
["b",0, 100, 100, 213, 43],
["c",0, 100, 100, 173, 0],
["d",0, 100, 100, 190, 84]
];
function scegli(parte) {
scelto = Math.floor(Math.random() * items.length);
document.getElementById("c" + parte).src = items[scelto];
}
function inizia() {
for (fh=0; fh<arraioParti.length; fh++) {
scegli(fh);
document.getElementById("c" + fh).style.width = arraioParti[fh][2] + "px";
document.getElementById("c" + fh).style.height = arraioParti[fh][3] + "px";
traspa("c" + fh);
}
}
function traspa(quale) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image();
img.src = document.getElementById(quale).src;
img.width = document.getElementById(quale).width;
img.height = document.getElementById(quale).height;
img.onload = function() {
c.width = img.width;
c.height = img.height;
ctx.drawImage(img, 0, 0, c.width, c.height);
}
var imgData = ctx.getImageData(0, 0, c.width, c.height);
for (var i=0; i<imgData.data.length; i+=4) {
if (imgData.data[i] == 255 && imgData.data[i+1] == 0 && imgData.data[i+2] == 255) {
imgData.data[i] = 255;
imgData.data[i+1] = 255;
imgData.data[i+2] = 255;
imgData.data[i+3] = 0;
}
}
ctx.putImageData(imgData, 0, 0);
document.getElementById(quale).src = c.toDataURL("image/png");
}
window.onload = inizia();