简体   繁体   中英

Fabric js rotate a image after it has been loaded with fabric.Image.fromURL

I have an image loaded using fabrics fabric.Image.fromURL

 fabric.Image.fromURL($scope.image, function(oImg)
            {
                oImg.set({width: $scope.imageWidth, height: $scope.imageHeight, originX:  'left', originY: 'top', selectable: false});
                canvas.add(oImg);
                canvas.centerObject(oImg);
                canvas.renderAll();
                oImg.sendToBack();
            });

What I want to do now is I have a rotation button on the page where they can rotate this image. however I cannot modify the image object after it's been loaded already. I've tried:

 oImg.rotate(90) 

but oImg is undefined now. Has anyone had any luck with this?

First off, I'd suggest using the .setAngle method as opposed to the .rotate.

But the root of your issue is how do you target that specific object.

Your oImg variable is localized to the function that is creating the object on the canvas. So simply setting oImg to a global variable allows you to target that object via a variable name.

var rotateThisImage;  /* Set this on a global scope outside of a function */
...
rotateThisImage = oImg;  /* Set oImg to your new global variable */
...
rotateThisImage.setAngle(curAngle+15);  /* Elsewhere in your code, on button click, set angle */

Here is an example of this: http://jsfiddle.net/PromInc/h9kL5bs0/

Another approach is to rotate only the active object on the canvas. For this to work though, the object would need to be selectable and you'd have to remove your selectable:false attribute.

canvas._activeObject

Canvas is the variable name for the canvas it self, and _activeObject is whatever object is selected on the canvas.

Here is an example of that - note that you have to select the object before it'll rotate. http://jsfiddle.net/PromInc/ckqk2Lzs/

Yet another approach that would allow you to keep the selectable:false attribute is to select the object by it's object id on the canvas.

canvas.item(0)

Item 0 is the first item on the canvas, which is the lowest in the layering order. If you had 5 objects on the canvas, the top most object would be item 4 as the indexing starts at 0.

Here is an example of this method: http://jsfiddle.net/PromInc/3efe2x9j/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM