[英]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.