How to move image in kineticjs on mousedown?

Member

by larissa , in category: Javascript , 4 months ago

How to move image in kineticjs on mousedown?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 4 months ago

@larissa 

To move an image in KineticJS on mousedown, you can follow these steps:

  1. First, create a KineticJS stage and layer as usual.
1
2
3
4
5
6
7
var stage = new Kinetic.Stage({
  container: 'container',
  width: 500,
  height: 500
});

var layer = new Kinetic.Layer();


  1. Create an image object and add it to the layer.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var imageObj = new Image();
imageObj.onload = function() {
  var image = new Kinetic.Image({
    x: 100,
    y: 100,
    image: imageObj,
    width: 100,
    height: 100
  });

  layer.add(image);
  stage.add(layer);
};
imageObj.src = 'path/to/image.jpg';


  1. Add mousedown event listener to the image object to handle the movement.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
var isDragging = false;

image.on('mousedown', function() {
  isDragging = true;
  this.moveToTop();
});

stage.on('mousemove', function() {
  if(isDragging) {
    var mousePos = stage.getPointerPosition();
    image.x(mousePos.x - image.width()/2);
    image.y(mousePos.y - image.height()/2);
    layer.draw();
  }
});

stage.on('mouseup', function() {
  isDragging = false;
});


This code creates an image object, adds it to the layer, and then adds mousedown, mousemove, and mouseup event listeners to handle the movement of the image when the user clicks and drags it. The image will move to the position of the mouse pointer on mousedown and will be released on mouseup.


You can further customize the movement behavior and add additional functionality as needed.