2015-05-11 40 views
0

TL; DR如何使圖像的畫布元素與圖像重疊在第二個畫布上。作爲與畫布重疊的畫布元素

我有兩個畫布元素。第一個有T恤的形象。第二個有可以手動添加的圖像。我想讓第二個畫布覆蓋第一個畫布。

JS:

var canvas = document.getElementById('first'); 
var context = canvas.getContext('2d'); 
context.fillStyle = '#fff'; 
context.fillRect(0, 0, canvas.width, canvas.height); 

var image = new Image(); 
image.src = 'http://neilhem.github.io/dressfor/images/raw-00.png'; 
image.onload = function() { 
    context.save(); 
    context.drawImage(image, 0, 0, canvas.width, canvas.height); 
    drawCustomLogo(context); 
} 

function drawCustomLogo(context) { 
    var layerCanvas = document.getElementById('second'); 
    var layerContext = layerCanvas.getContext('2d'); 
    var image = new Image(); 
    image.src = 'http://neilhem.github.io/dressfor/images/forest/pattern.png'; 
    image.onload = function() { 
     context.save(); 
     context.drawImage(image, 0, 0, 265, 265); 
    } 
    context.globalCompositeOperation = 'overlay'; 
    context.drawImage(layerCanvas, 100, 70); 
} 

我沒有在http://codepen.io/neilhem/pen/JdGZKx

一些例子正如你可以看到疊加的圖像較淡,如何使結果不那麼輕?

回答

1

你想要的是從globalCompositeOperation屬性source-atop類型。

而且,在你的代碼,你從來沒有讓我刪除它

var canvas = document.getElementById('first'); 
 
var context = canvas.getContext('2d'); 
 
context.fillStyle = 'rgba(0,0,0,0)'; 
 
context.fillRect(0, 0, canvas.width, canvas.height); 
 

 
var image = new Image(); 
 
image.src = 'http://neilhem.github.io/dressfor/images/raw-00.png'; 
 
image.onload = function() { 
 
    context.drawImage(image, 0, 0, canvas.width, canvas.height); 
 
    drawCustomLogo(context); 
 
} 
 

 
function drawCustomLogo(context) { 
 
    var image = new Image(); 
 
    image.src = 'http://neilhem.github.io/dressfor/images/forest/pattern.png'; 
 
    image.onload = function() { 
 
    context.save(); 
 
    context.globalCompositeOperation = "source-atop"; 
 
    context.drawImage(this, 0, 0); 
 
    } 
 
}
body { 
 
    background-color: #000; 
 
}
<canvas id="first" width="547" height="646"></canvas>

詩用你的第二畫布:你可能還需要改變
context.fillStyle = '#FFF';context.fillStyle = 'rgba(0,0,0,0)';

+0

我希望第二個畫布是第一個畫布的疊加圖像。像這裏http://codepen.io/neilhem/pen/pJgKep在這個例子中,只有在襯衫內部可見模式 – neilhem

+0

@neilhem從代碼中看不到它,請參閱編輯 – Kaiido

+0

http://codepen.io/neilhem/pen/pJgKep這是我想要實現的,只是當我使用圖像作爲覆蓋圖像時,它的一個區別變得太輕。 – neilhem