3

I have a panel for creating something using canvas fabric js. Canvas has many placeholders like a rectangle and I want to add images in that particular area. I am making that area clipped so that the image does not leave that area. Now everything is working fine except that the clipping area does not set angle (Rotate is not working) using canvas instance.

Here is my code:

var clipByName = function (bindClip) {

    this.setCoords();
    var clipRect = findByClipName(this.clipName);
    var scaleXTo1 = (1 / this.scaleX);
    var scaleYTo1 = (1 / this.scaleY);
    bindClip.save();

    var ctxLeft = -( this.width / 2 ) + clipRect.strokeWidth;
    var ctxTop = -( this.height / 2 ) + clipRect.strokeWidth;
    var ctxWidth = clipRect.width - clipRect.strokeWidth;
    var ctxHeight = clipRect.height - clipRect.strokeWidth;

    bindClip.translate(ctxLeft, ctxTop);


    bindClip.rotate(this.angle *(Math.PI / 180) * -1);
    bindClip.scale(scaleXTo1, scaleYTo1);

    bindClip.beginPath();
    bindClip.rect(
        clipRect.left - this.oCoords.tl.x,
        clipRect.top - this.oCoords.tl.y,
        clipRect.width,
        clipRect.height
    );
    console.log(bindClip);
    bindClip.closePath();
    bindClip.restore();
}

This is the URL where I want to see those changes. Try adding images by drag and drop. https://purplle.com/collection/create-collection/?template=175

Kindly follow the below details:

  1. Search for products, for example, Lakme, Ponds, etc.
  2. Drag any image to the product placeholder.

When moving the image, the clipping area is still not getting the angle of the current placeholder (Rectangle).

Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36
Jugal Singh
  • 118
  • 7
  • Try to add stroke color on clipping, may be it will help you to debug. and also add angle in clipping same as you added on rect – devesh singhal Sep 16 '15 at 05:10

2 Answers2

3

Try this fiddle, it might help you http://jsfiddle.net/ZxYCP/194/

clipTo: function(ctx) { 
  ctx.save();
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.rect(
    100, 100,
    200, 200
  );
  clipRect1.render(ctx);
  ctx.strokeStyle = "red";
  ctx.stroke();
  ctx.restore();
}
Mayank Saxena
  • 152
  • 1
  • 12
1

You may also try this one: http://jsfiddle.net/ZxYCP/198/

var clipPoly = new fabric.Polygon([
    { x: 180, y: 10 },
    { x: 300, y: 50 },
    { x: 300, y: 180 },
    { x: 180, y: 220 }
], {
    originX: 'left',
    originY: 'top',
    left: 180,
    top: 10,
    width: 200,
    height: 200,
    fill: '#DDD', /* use transparent for no fill */
    strokeWidth: 0,
    selectable: false
});

You can simply use Polygon to clip. Answer is based on @natchiketa idea in this question Multiple clipping areas on Fabric.js canvas

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
l00k
  • 1,525
  • 1
  • 19
  • 29