簡體   English   中英

在畫布中更改顏色圖像

[英]Change color Image in Canvas

我想在畫布中更改圖像的顏色

這是形象

在此輸入圖像描述

你可以看到有一個圖像透明我嘗試使用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);

要手動混合,您必須應用不同的公式來混合前景(新顏色)和背景(圖像)以保留消除鋸齒的像素(以防萬一:問題中包含的圖像實際上不是透明的,但我想你只是試圖用固體棋盤背景說明透明度?)。

我建議采用一種不同的方法,即CORS安全且更快(更簡單) -

有兩種方法可以做到這一點:一種是繪制你想要的顏色,然后將復合模式設置為destination-in然后繪制圖像,或者繪制圖像,將復合模式設置為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); } 
 <canvas id=c></canvas> 

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

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

getImageData() ,此技術的缺點是您的畫布必須僅在執行此過程時保留此圖像的內容。 如果圖像需要着色並與其他內容混合,則解決方法是使用離屏畫布進行處理,然后將該畫布繪制回主畫布。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM