Recently, there was a demand to change the color of the picture.
I actually turned it down because I said it was hard to do. But I did.
Here’s how to change colors. The effect is ok. so-so
The main code is still copied from someone else. I’ll just write that down for the record
1. Composition of pictures generated by Canvas getImageData
According to the cycle
Image composition is ARGB format, the first is transparency, followed by RGBA
2. The resulting picture cycle needs to be circulated by a multiple of 4, otherwise it will be stuck at least
for (var j = 0; j < pdata.length; j+=4) {
if (pdata[j] === 95) pdata[j] = colorArr[0];
if (pdata[j - 1] === 170) pdata[j-1] = colorArr[1];
if (pdata[j - 2j] === 129) pdata[j-2] = colorArr[2];
}
Copy the code
3. Note that the replacement colors should be in reverse order
So 0,1,2,3
The replacement RGB color should be 3,2,1
Get array RGB: data[I],data[i-1],data[2]
For substitution, see the code above
4. Complete code format
<! DOCTYPE html> <html> <style>#btn {
width: 100px;
height: 50px;
background: coral;
position: fixed;
top: 0;
}
</style>
<head>
<script type="text/javascript">
var c, ctx,myImage;
function displayImage() {
myImage = new Image();
myImage.src = "1719ebbc83be39f0.webp.jpg";
c = document.getElementById("myCanvas");
if (c.getContext) {
ctx = c.getContext("2d");
myImage.onload = function() { ctx.drawImage(myImage, 0, 0); }}} //colorArr Color after replacement //color before replacementfunction getColorData(colorArr, color2) {
imageD = ctx.getImageData(0, 0, myImage.width, myImage.height);
var pdata = imageD.data;
for (var j = 0; j < pdata.length; j+=4) {
if (pdata[j] === color2[0]) pdata[j] = colorArr[0];
if (pdata[j + 1] === color2[1]) pdata[j + 1] = colorArr[1];
if (pdata[j + 2] === color2[2]) pdata[j + 2] = colorArr[2];
}
ctx.putImageData(imageD, 0, 0);
}
function colorChange() {// RGB color getColorData([102, 51, 153], [95, 170, 129]); } </script> </head> <body onload="displayImage()"</p> <img id="myPhoto" src="1719ebbc83be39f0.webp.jpg"Canvas picture: </p> < Canvas ID ="myCanvas" width="200" height="200"></canvas>
<button id="btn" onclick="colorChange()"Word-wrap: break-word! Important; "> </button> </body> </html>Copy the code