Using image mask with globalCompositeOperation on KonvaJS?

我与影子孤独终老i 提交于 2021-01-27 10:44:15

问题


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 ?

Best

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:


The problem was that you needed to:

1. add a new layer: let layer2 = new Konva.Layer();
2. add it to the stage in the correct order: stage.add(layer2, layer);

Here is the updated:
jsfiddle example



来源:https://stackoverflow.com/questions/46557532/using-image-mask-with-globalcompositeoperation-on-konvajs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!