Search code examples
vue.jskonvajs

How to create collisions in Konva.js


someone knows how to create collisions of layers in Vue.js using Konva.js? For example i have a square and in the middle is small dot. What i want is to block dot inside a square. We can drag dto around but we can't drag it out of the square. I would be really grateful for help :D

  var vm = this;
  const stage = vm.$refs.stage.getStage();

  var layer = new Konva.Layer();
  var group = new Konva.Group({
    x: 100,
    y: 100,
    draggable: false
  });
  var text = new Konva.Text({
    x: 10,
    y: 10,
    fontFamily: "Calibri",
    fontSize: 24,
    text: "",
    fill: "black"
  });
  var rect = new Konva.Rect({
    clearBeforeDraw: true,
    x: 50,
    y: 50,
    width: 100,
    height: 50,
    fill: "green",
    stroke: "black"
  });
  var circle = new Konva.Circle({
    clearBeforeDraw: true,
    x: this.x,
    y: this.y,
    radius: 10,
    fill: "red",
    stroke: "black",
    strokeWidth: 4,
    containment: rect,
    draggable: true,
    name: "fillShape"
  });
  circle.on("dragmove", function() {
    that.x = this.getX();
    that.y = this.getY();
  });
  group.add(rect, circle);
  layer.add(group);
  stage.add(layer);

Solution

  • Add dragBoundFunc in circle object and set limits to absolute width and height of rectangle

    var circle = new Konva.Circle({
        clearBeforeDraw: true,
        x: 75,
        y: 75,
        radius: 10,
        fill: "red",
        stroke: "black",
        strokeWidth: 4,
        containment: rect,
        draggable: true,
        name: "fillShape",
        dragBoundFunc: function(pos) {
            const x = Math.min(250-12, Math.max(pos.x, 150+12));
            const y = Math.min(200-12, Math.max(pos.y, 150+12));
            return {x, y};
       }
    });