Search code examples
konvajs

Drawing rectangle can not shadow my image


I am trying to drawing something over an existing image object using Konvajs. so I code like this:

var stage = new Konva.Stage({
    container: 'underground-map-container',
    width: window.innerWidth,
    height: 1121.6
});

var layer = new Konva.Layer();

var imageObj = new Image();
imageObj.onload = function () {
    var parking_img = new Konva.Image({
        image: imageObj,
        width: 1328,
        height: 878.6
    });
    layer.add(parking_img);
    stage.add(layer);
};
imageObj.src = "../static/img/underground-map.png";


var rect = new Konva.Rect({
    x: 700,
    y: 50,
    width: 200,
    height: 200,
    fill: 'blue',
    opacity:1
});
layer.add(rect);

var rect1 = new Konva.Rect({
    x: 800,
    y: 50,
    width: 200,
    height: 200,
    fill: 'red',
    opacity:1
});
layer.add(rect1);

rect1 can shadow rect, however, both of them can not shadow my image. Does anyone know how to do that, thank you!

following is the actual output


Solution

  • The image is added to a layer when it is loaded. It happens AFTER rectangles are added, so the image is placed on top. To move the image you can use:

    1. parking_img.moveToBottom()
    2. or parking_img.setZIndex(0)

    Important: Use those methods only after you added the image to a layer like:

    var parking_img = new Konva.Image({
        image: imageObj,
        width: 1328,
        height: 878.6
    });
    layer.add(parking_img);
    parking_img.moveToBottom();
    layer.draw();