Konva js fillPatternImage issues

66 Views Asked by At

I'm having a little trouble with the fillPatternImage function

Here is the sample bench: https://codepen.io/adrienreveleau/pen/xxMNJZX
And here's the failure case: https://jsbin.com/dusocukeya/edit?js,output

Despite deep research and several attempts to adjust the offsets parameters, I haven't succeeded in finding a solution!

Could you help me?

1

There are 1 best solutions below

1
On BEST ANSWER

Your konvaImage has a different size from the original image. So you need to take that into account when calculating patter offset.

   let d = { width: 498, height: 665.1085141903172 }

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

let layer = new Konva.Layer();
stage.add(layer);

 let konvaImage = new Konva.Image({
width: d.width,
height: d.height,
  });

let img = new Image();
img.onload = function () {
  // Ajouter l'image à la couche
  layer.add(konvaImage);
   konvaImage.image(img);
};

img.src = 'https://64.media.tumblr.com/tumblr_mapvkz4afv1qiehnjo1_640.jpg';

let magnifierLayer = new Konva.Layer();
stage.add(magnifierLayer);
let zoom = [4, 2, 1]

let magnifier = new Konva.Circle({
  radius: 50 * 2, 
  fillPatternImage: img,
  fillPatternScale: { x: zoom[1], y: zoom[1] }, 
  fillPatternOffset: { x: 100, y: 100 },
  stroke: 'black',
  fillPatternRepeat: 'no-repeat',
  opacity: 1,
  strokeWidth: 2,
});
magnifierLayer.add(magnifier);

stage.on('mousemove', function (e) {
  const scaleX = konvaImage.width() / d.width;
  const scaleY = konvaImage.height() / d.height;
  let pos = stage.getPointerPosition();
  magnifier.position(pos);
  magnifier.fillPatternOffset({ x: img.width * (pos.x / konvaImage.width()), y: img.height * (pos.y / konvaImage.height())});
});

document.getElementById('container').style.cursor = 'none';
 <script src="https://unpkg.com/konva@9/konva.min.js"></script>
<div id="container">