上将图像蒙版与globalCompositeOperation一

上将图像蒙版与globalCompositeOperation一

本文介绍了在KonvaJS上将图像蒙版与globalCompositeOperation一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Konva.js框架,并尝试在另一个框架上应用图像蒙版.该代码已从此帖子中完全复制.在这个 jsfiddle示例中,做了一些小的修改以添加背景(Rect).

I am using Konva.js framework and trying to apply an image mask over an other one.The code is fully copied from this post.In this jsfiddle example there is small modifications to add a background (Rect).

问题是背景没有正确绘制.要在代码中看到它的实际效果,请在一行中添加注释/取消注释(以查看该问题的实际效果).有人有什么想法要实现这一目标吗?

The problem is that the background is not properly drawn. To see it in action in the code there is a line to comment/uncomment (to see the problem in action).Is someone have any idea to achieve this ?

最佳

let stage = new Konva.Stage({
    container: 'container',
    width: window.innerWidth,
    height: window.innerHeight
});

let layer = new Konva.Layer();
let rect = new Konva.Rect({
    x: 0,
    y: 0,
    width: 900,
    height: 900,
    draggable: true,
    fill: '#ff8619',
});

// -------------------------------------
// Line to comment or uncomment
//layer.add(rect);
// -------------------------------------

stage.add(layer);

let mask = new Image();
mask.onload = () => {
    let img = new Image();
    img.onload = () => {
        let image = new Konva.Shape({
            sceneFunc: (ctx) => {
                ctx.save();
                ctx.drawImage(mask, -image.x(), -image.y(),  200, 200);
                ctx.globalCompositeOperation = 'source-in';
                ctx.drawImage(img, 0, 0, 200, 200);
                ctx.globalCompositeOperation = 'source-over';
                ctx.restore();
            },
            // (!) important
            // for this case you need to define custom hit function
            hitFunc: (ctx) => {
                ctx.rect(0, 0, 200, 200);
                ctx.fillStrokeShape(image);
            },
            draggable: true
        });
        layer.add(image);
        layer.draw();
    };
            img.src = "http://i.imgur.com/kKjW3U4.png";

};
        mask.src = "http://i.imgur.com/fQX2P8S.png";

推荐答案

问题是您需要:

1.添加一个新层: let layer2 = new Konva.Layer();
2.按照正确的顺序将其添加到舞台: stage.add(layer2,layer);

这是更新的内容:
jsfiddle 示例

这篇关于在KonvaJS上将图像蒙版与globalCompositeOperation一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 15:29