TL; DR如何使带有图像的canvas元素与图像叠加在第二个画布上。
我有两个画布元素。第一个有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
中做了一些例子正如您所看到的,重叠图像更轻,如何使结果不那么轻?
答案 0 :(得分: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>
Ps:您可能还想更改
context.fillStyle = '#FFF';
至context.fillStyle = 'rgba(0,0,0,0)';