0
votes

I'm trying to rotate an image added to my canvas using KineticJS. I got it almost working. I know I need to set the offset to 'move' the rotation point, that part is working. But it is also moving to that location of the offset. After doing some rotating I can drag my image to another location in the canvas and continue rotating around its own center. I don't want to rotate the whole canvas, because I have multiple images on a layer.

The relevant code:

function rotateLayer() {
    // Rotate bird image
    var rotation = 15;

    // Set rotation point:
    imageDict[1].setOffsetX(imageDict[1].width() / 2);
    imageDict[1].setOffsetY(imageDict[1].height() / 2);

    // rotation in degrees
    imageDict[1].rotate(rotation);
    imageDict[1].getLayer().draw();
}

A working demo is on jsfiddle: http://jsfiddle.net/kp61vcfg/1/

So in short I want the rotation but not the movement.

2

2 Answers

1
votes

How you want to rotate without movement? KineticJS rotate objects relative it's "start point" . For example for Kinetic.Rect start points is {0, 0} - top left corner. You may move such "start point" to any position with offset params.

0
votes

After a lot of trail and error I found the solution.

The trick is to set the offset during load to the half width and height to set the rotation point to the middle of the image AND don't call image.cache:

function initAddImage(imgId, imgwidth, imgheight) {
    var imageObj = new Image();
    imageObj.src = document.getElementById(imgId).src;
    imageObj.onload = function () {
        var image = new Kinetic.Image({
            image: imageObj,
            draggable: true,
            shadowColor: '#787878',
            shadowOffsetX: 2,
            shadowOffsetY: 2,
            width: imgwidth,
            height: imgheight,
            x: 150,  // half width of container
            y: 150,  // half height of container
            offset : {x : imgwidth / 2, y : imgheight / 2}, // Rotation point
            imgId: imgId
        });

        layer.add(image);
        //image.cache();
        layer.draw();
        imageDict[currentLayerHandle] = image;
        currentLayerHandle++;
    };
}

I've updated my demo to a working version: http://jsfiddle.net/kp61vcfg/2/