@larissa
To move an image in KineticJS on mousedown, you can follow these steps:
1 2 3 4 5 6 7 |
var stage = new Kinetic.Stage({ container: 'container', width: 500, height: 500 }); var layer = new Kinetic.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 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.