使用目标输出合成擦除 EaselJS 中的部分位图

Erasing parts of a bitmap in EaselJS using destination-out compositing

我在使用某些功能时遇到了一些困难。我正在尝试使用 easelJS 创建橡皮擦并擦除图像的一部分。我见过其他人这样做,但只是擦除其他图形 - 当我尝试擦除图像时,我什么也做不了。如果我想擦除位图而不是其他图形,这可能吗?

我也尝试过使用 AlphaMaskFilter,但它给我的结果与我正在寻找的完全相反(它掩盖了所有内容,并且只显示了我绘制的内容)。

var c = createjs, stage, art;
var x, y, listener, color, hue=0;

stage = new c.Stage("test");
var testImg = new c.Bitmap("http://lorempixel.com/output/animals-q-c-640-480-5.jpg");

art = stage.addChild(testImg, new c.Shape());
art.cache(0,0,600,400);

stage.on("stagemousedown", startDraw, this);

function startDraw(evt) {
    listener = stage.on("stagemousemove", draw, this);
    stage.on("stagemouseup", endDraw, this);
    color = c.Graphics.getHSL(hue+=85, 50, 50);
    x = evt.stageX-0.001; // offset so we draw an initial dot
    y = evt.stageY-0.001;
    draw(evt); // draw the initial dot
}

function draw(evt) {
    art.graphics.ss(20,1).s(color).mt(x,y).lt(evt.stageX, evt.stageY);

    // the composite operation is the secret sauce.
    // we'll either draw or erase what the user drew.
    art.updateCache(erase.checked ? "destination-out" : "source-over");

    art.graphics.clear();
    x = evt.stageX;
    y = evt.stageY;
    stage.update();
}

function endDraw(evt) {
    stage.off("stagemousemove", listener);
    evt.remove();
}

http://jsfiddle.net/17xec9y5/8/

您的示例仅影响您缓存的 Shape 实例。当您在 addChild() 中使用多个参数时,它 returns 最后添加的项目,因此在您的示例中, art 变量仅引用形状。所以图像就在您要绘制的 "painted area" 下方。

要解决此问题,请创建并缓存一个容器。一些小的补充:

  1. 图像加载后,更新一次缓存(以应用图像)。
  2. 然后删除图像,以便在每次绘制时更新缓存时不再应用它。

就是这样!

这是一个fiddle: http://jsfiddle.net/lannymcnie/17xec9y5/9/

相关代码:

// Listen for the image load
testImg.image.onload = function() {
    cont.updateCache("source-over"); // Update cache once
    cont.removeChild(testImg); // Remove image

    stage.update(); // Draw the stage to see the image
}

// Create a sub-container that will hold the art and image 
var cont = stage.addChild(new c.Container());
art = new c.Shape(); // Art is just the shape
cont.cache(0,0,600,400); // Cache the container instead
cont.addChild(testImg, art);

// Then, later update the container's cache (instead of the art)
cont.updateCache(erase.checked ? "destination-out" : "source-over");