Search code examples
javascripthtmlcsscanvaskonvajs

Canvas Shape Scaling


I'm using canvas with konva library and I'm trying to scale the canvas element. I can easily scale it down with CSS but the problem is the shapes that I have drawn in there are clickable. When the canvas scales down the elements do as well but their mask or the clickable area does not. Meaning that if i click on the shapes on a down scaled canvas nothing happens as the click mask is on a different position and in same scale as the original.

Question is how can I scale the shape click mask along side with the canvas base?

var stage = new Konva.Stage({
  container: 'container',
  width: 500,
  height: 500
});
for (var i = 0; i < shapes.length; i++) {
  var s = shapes[i];
  var links = document.getElementsByClassName(s.link);
  var poly = new Konva.Line({
    points: s.points,
    fill: 'red',
    stroke: 'black',
    strokeWidth: 5,
    closed: true,
    opacity: 0
  });

  poly.on('mousedown touchstart', function () {
    var polyfind = stage.find('Line');
    for (var i = 0; i < polyfind.length; i++) {
      polyfind[i].opacity(0);
    }

  }
  layer.add(poly);
}

Shapes come from json file

"Shapes": [
  {
    "points": [ 100, 100, 150, 100, 150, 150, 100, 150 ],
    "link": "A",
  }
]

On CSS side its just max-width: 100%; etc. Even tried CSS Zoom option but it had the same results as max-width on the shape click masks.


Solution

  • Do not use CSS for scale.

    Use stage.scale() method to set your values. Probably you will need to change size of a stage too.