画布元素作为画布的叠加

时间:2015-05-11 10:12:58

标签: html5 canvas html5-canvas

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

中做了一些例子

正如您所看到的,重叠图像更轻,如何使结果不那么轻?

1 个答案:

答案 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)';