Change color Image in Canvas

后端 未结 1 585
独厮守ぢ
独厮守ぢ 2020-12-10 18:24

I want to change color a Image in canvas

this is the Image

You can see there is a Image transparent I was try using PutImgData but my transparent is

1条回答
  •  醉梦人生
    2020-12-10 18:34

    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);
    }

    Example using second approach:

    var img = new Image; img.onload = draw; img.src = "//i.stack.imgur.com/cZ0gC.png";
    var ctx = c.getContext("2d");
    
    function draw() {
      // draw image
      ctx.drawImage(this, 0, 0);
    
      // set composite mode
      ctx.globalCompositeOperation = "source-in";
    
      // draw color
      ctx.fillStyle = "#09f";
      ctx.fillRect(0, 0, c.width, c.height);
    }

    To reset comp. mode back to normal use:

    // reset comp. mode
    ctx.globalCompositeOperation = "source-over";
    

    As with getImageData(), the drawback with this technique is that your canvas must only hold the content of this image while doing this process. A workaround if the image needs to be colored and mixed with other content is to use an off-screen canvas to do the processing, then draw that canvas back onto the main canvas.

    0 讨论(0)
提交回复
热议问题