2

I'm working on a small script that lets a user load a custom image into the canvas on the webpage. So far that works pretty neat. The canvas is initialized using the fabric.js script in order to let the user do some easy editing tasks.

The "uploaded" image is clipped by a simple rectangle. Now comes the tricky part: the user should then be able to move around, scale and rotate the image, whilst the rectangle stays in place; selecting the image section preferred. However, even

lockMovement = true;

or

lockMovementX = true;    
lockMovementY = true;    

do not keep that clipping mask in place. Any other way to achieve this?

Any help is greatly appreciated! Please find a demo here: http://jsfiddle.net/efmbrm4v/

t0bias
  • 93
  • 3
  • 13

1 Answers1

6

I had the same problem and I solved it with following code:

image.clipTo = function (ctx) {
  ctx.save();

  ctx.setTransform(1, 0, 0, 1, 0, 0); // Reset transformation to default for canvas
  ctx.rect(
    100, 100, // Just x, y position starting from top left corner of canvas
    200, 200 // Width and height of clipping rect
  );

  ctx.restore();
};

You can try it out here: http://jsfiddle.net/Jagi/efmbrm4v/1/

Łukasz Jagodziński
  • 3,009
  • 2
  • 25
  • 33
  • Good Point! This is indeed very close to what I am looking for, however I'm trying to achieve that the user can still rotate, scale, skew, etc. the clipped image. So far I managed to "get back" the controls/handles around the image, nonetheless scaling, rotating, or whatsoever does not work as intended: the clipping mask is transformed together with the image equally. – t0bias Jan 14 '15 at 13:27
  • Hmm could you describe in details what do you want to achieve? I think that we misunderstood each other. In my example the clipping mask stays always in the same position. And you can move, rotate, scale and skew image as you wish. Or maybe you wanted to move, rotate, scale and skew the mask? – Łukasz Jagodziński Jan 14 '15 at 13:32
  • 4
    Checkout this example http://jsfiddle.net/efmbrm4v/2/. You can move, scale etc. the mask while still be able to move, scale etc. the image. – Łukasz Jagodziński Jan 14 '15 at 13:37
  • Hi, after applying move, scale and rotate to the maks image. is it possible to make the rect and mask image as single object? – Karthick Kumar Nov 07 '16 at 04:18
  • @Jagi: I am facing the same issue, Did you find any solution for this problem? If yes can you post your solution here, please? – Dr. Piyush Dholariya Jul 08 '19 at 10:37