Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to change color a Image in canvas

this is the Image

enter image description here

You can see there is a Image transparent I was try using PutImgData but my transparent is changing color Is there anyway to change color the car and money only ? I was using this code :

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    image = document.getElementById("testImage");
canvas.height = canvas.width = 100;
ctx.fillStyle = 'red';
ctx.fillRect(10,10,20,10);
ctx.drawImage(image,0,0);

var imgd = ctx.getImageData(0, 0, 45, 45),
    pix = imgd.data;

for (var i = 0, n = pix.length; i <n; i += 4) {
    if(pix[i+3]==0)
  {continue;}
    pix.length[i]=r|pix.length[i];
  pix.length[i+1]=g|pix.length[i+1];
  pix.length[i+2]=b|pix.length[i+2];
   pix[i + 3] = 255;
}

ctx.putImageData(imgd, 0, 0);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
181 views
Welcome To Ask or Share your Answers For Others

1 Answer

To mix manually you would have to apply a different formula to mix foreground (new color) and background (image) to preserve anti-aliased pixels (and just in case: the image included in the question is not actually transparent, but I guess you just tried to illustrate transparency using the solid checkerboard background?).

I would suggest a different approach which is CORS safe and much faster (and simpler) -

There are a couple of ways to do this: one is to draw in the color you want, then set composite mode to destination-in and then draw the image, or draw the image, set composite mode to source-in and then draw the color.

Example using the first approach coloring the following image blue:

image

var img = new Image; img.onload = draw; img.src = "//i.stack.imgur.com/cZ0gC.png";
var ctx = c.getContext("2d");

function draw() {
  // draw color
  ctx.fillStyle = "#09f";
  ctx.fillRect(0, 0, c.width, c.height);
  
  // set composite mode
  ctx.globalCompositeOperation = "destination-in";
  
  // draw image
  ctx.drawImage(this, 0, 0);
}
<canvas id=c></canvas>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...