javascript - 如何向 Canvas 元素添加蒙版和背景

标签 javascript html5-canvas

我正在尝试制作一个由带有背景图像的 png 遮盖的图像。当我仅放置蒙版图像时效果很好,但如果我添加背景图像,则正面图像不再被蒙版

<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  var bg = new Image();
  var front = new Image();
  var mask = new Image();

  bg.src = 'img/background.jpg';

  bg.onload = function() {
    front.src = "img/tobemasked.jpg";
  };

  front.onload = function() {
    mask.src = "img/mask.png";
  }

  mask.onload = function() {
    display();
  }

  function display() {
    context.drawImage(bg, 0, 0); // it works if i remove this line
    context.drawImage(tmpMask, 0, 0);
    context.globalCompositeOperation = "source-in";
    context.drawImage(front, 0, 0);
  }
</script>

我想这是一个很常见的问题,但我在网络上找不到任何相关内容。

感谢您的帮助。

最佳答案

用于屏蔽正面图像的“source-in”操作在此处定义 http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#gcop-source-in像这样:

Display the source image wherever both the source image and destination image are opaque. Display transparency elsewhere.

在不绘制背景图像的情况下,目标图像仅由您的蒙版组成,并且据说具有透明像素。仅当 mask 不透明时才会显示正面图像。我明白这就是你想要的。

但是,当你也绘制了背景图像之后,目标图像中应该没有透明像素,它是完全不透明的,当你绘制正面图像时,它的所有部分都会显示。

这将完成我认为你正在尝试做的事情:

context.drawImage(mask, 0, 0);
context.globalCompositeOperation = "source-in";
context.drawImage(front, 0, 0);
context.globalCompositeOperation = "destination-atop";
context.drawImage(bg, 0, 0);

首先屏蔽正面图像。之后仍然有透明像素。使用“destination-atop”选项将背景图像绘制在透明区域上(请参阅前面的链接)。

我认为这是最简单的方法。其他一些选项是使用多个 Canvas 元素相互叠加来创建图层,或使用一些 javascript 库,使图层与 Canvas 一起使用成为可能。

关于javascript - 如何向 Canvas 元素添加蒙版和背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16505118/

相关文章:

php - 如何将 JavaScript 变量传递给 PHP?

html5-canvas - Three.JS - 无皮肤 DAE 动画

html5-canvas - 图层旋转后 KineticJS 鼠标位置错误

HTML5 Canvas 背景图片

javascript - 使用 <canvas> 处理大型 'map'

javascript - 从 ngDialog 模式修改 FullCalendar 事件信息(开始和结束)

javascript - Bootstrap 轮播忽略数据间隔属性

javascript - 导出 * as blabla - 意外的 token 错误

javascript - jQuery 插件回调无法正常工作

javascript - 在fabricjs中加载和存储svg文件