1
votes

I am using KineticJS and to this point it has been a great experience. One question I have though is about dragging. I have the image in this example set to 'draggable: true', but after I drag it the first time, it cannot be moved again.

var stage = new Kinetic.Stage({
    container: 'container',
    width: 2754,
    height: 1836
});
var layer = new Kinetic.Layer();
var scale = '0.16339869281045751633986928104575';
var imageObj = new Image();
imageObj.onload = function () {
    var img = new Kinetic.Image({
        x: 0,
        y: 0,
        height:612,
        width:612,
        image: imageObj,
        draggable: true,
        dragBoundFunc: function (pos) {
            console.log(img.getAttrs());
            return { 
                x: Math.floor((pos.x/scale)/306)*306,
                y: Math.floor((pos.y/scale)/306)*306 
                };
        }
    });

    // add the shape to the layer
    layer.add(img);

    // add the layer to the stage
    stage.add(layer);

};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg';

http://jsfiddle.net/7UEC6/

Any help is appreciated. For extra credit you can suggest ways to make the dragging smoother in general.

Thanks!

edit: I have noticed that after the image is dragged the initial time, the dragBoundFunc is no longer called when the user tries to drag the image

it also works if i drag the image back to 0,0 but no other time

1

1 Answers

2
votes

This is not possible with current KineticJS.

Let me try to explain why.

When you use transform:scale, which is CSS3 element(not standard yet), the visual position of actual elements gets also scaled. However the relative mouse position of MouseEvent only passes visual position(not scaled position).

The mouse click event for dragging, which KineticJS uses, only reads MouseEvent position, which is visual one(not scaled one), and it does not consider transformation of canvas element.

When you set your image x/y to following, you cannot even do the first drag

    x: 612,
    y: 612,

However when you set it as 0 and 0, it respond to it because the scaled and unscaled position is the same.

For the above example x/y 612 and 612, you cannot click to drag, because KineticJS understand it as you are not clicking 612 and 612, but it think it as 100 and 100

The reason is simple as I explained.

MouseEvent does not pass scaled X/Y, but visual position of X/Y.

Who knows when CSS3 become standard, it might be well supported :)

Meanwhile, I would not recommend to use transformation with canvas. Unless you build your own framework, it is pretty hard to make all things correctly with canvas transformed.