在画布中更改颜色图像

时间:2017-08-16 06:50:21

标签: javascript jquery html5 canvas

我想改变画布中的图像颜色

这是图像

enter image description here

你可以看到有一个图像透明我尝试使用PutImgData,但我的透明正在改变颜色 反正有改变汽车和金钱的颜色吗? 我使用的是这段代码:

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

1 个答案:

答案 0 :(得分:7)

要手动混合,您必须应用不同的公式来混合前景(新颜色)和背景(图像)以保留消除锯齿的像素(以防万一:问题中包含的图像实际上不是透明的,但是我想你只是试图用固体棋盘背景说明透明度?)。

我建议使用另一种方法,即CORS安全且更快(更简单) -

有两种方法可以做到这一点:一种是绘制你想要的颜色,然后将复合模式设置为destination-in,然后绘制图像,或绘制图像,将复合模式设置为{{ 1}}然后绘制颜色。

使用第一种方法将以下图像着色为蓝色的示例:

image

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

重置comp。模式恢复正常使用:

<canvas id=c></canvas>

// reset comp. mode ctx.globalCompositeOperation = "source-over"; 一样,此技术的缺点是您的画布只能在执行此过程时保留此图像的内容。如果图像需要着色并与其他内容混合,则解决方法是使用离屏画布进行处理,然后将该画布绘制回主画布。