通过绘图/描边/绘画在画布上显示图像

Ale*_*lex 1 html javascript html5-canvas

我想实现以下目标:

  1. 将背景图像绘制到画布上(一次或如果需要重复)
  2. 图像一开始不应该是可见的
  3. 当我在画布上“绘制”形状时,背景图像应该在绘制形状的地方可见

将显示的图像部分将被“绘制”(就像用画笔一样),所以我想使用笔触。

我尝试过的: - 不要清除画布 - 使用 globalCompositeOperation = 'destination-in' 将矩形绘制到画布上 这有效,矩形显示图像,但我需要笔划

如果我使用笔画,它们会被“destination-in”忽略,而我会使用正常的 globalCompositeOperation 看到它们。

这是为了忽略笔划吗?是否有解决方法,例如以某种方式将笔画/形状转换为位图?或者我必须使用两个画布元素吗?

在 OpenGL 中,我首先用它的 rgb 值和 a = 0 绘制图像,然后只“绘制”alpha。

小智 6

您可以通过以下步骤解决:

  • 将图像设置为图案
  • 将模式设置为fillStylestrokeStyle

当您现在填充/描边形状时,图像将会显示。只需确保初始图像适合您想要显示的区域即可。

显示原理的示例,您应该能够根据您的需要采用它:

var ctx = canvas.getContext("2d"),
    img = new Image,
    radius = 40;

img.onload = setup;
img.src = "http://i.imgur.com/bnAEEXq.jpg";

function setup() {
  
  // set image as pattern for fillStyle
  ctx.fillStyle = ctx.createPattern(this, "no-repeat");
  
  // for demo only, reveals image while mousing over canvas
  canvas.onmousemove = function(e) {
    var r = this.getBoundingClientRect(),
        x = e.clientX - r.left,
        y = e.clientY - r.top;
    
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.arc(x, y, radius, 0, 2*Math.PI);
    ctx.fill();
  };
}
Run Code Online (Sandbox Code Playgroud)
<canvas id=canvas width=900 height=600></canvas>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!