Skip to content Skip to sidebar Skip to footer

Fabric Todataurl With Multiplier Not Working As Expected

In my code I created method to clip images using fabric shapes. I have used stackoverflow answer for achieving this. Somehow after using this method I cannot render the canvas usin

Solution 1:

Your problem is the multiplier. When using that kind of clipTo functions, you are setting the transform of canvas to plain. When rendering with canvas with multiplier, the base canvas transformation is scaled by the multiplier.

Your rect will be drawn without this transform ( because of setTransform(1,0,0,1,0,0) and will clip out the image.

Instead of setting the transform to [1,0,0,1,0,0] you should set to the invers of the current transformation of the object you are clipping.

var img01URL = 'https://www.google.com/images/srpr/logo4w.png';
var img02URL = 'http://fabricjs.com/lib/pug.jpg';

var canvas = new fabric.Canvas('c');

document.getElementById('download').addEventListener('click', function() {
  var data = canvas.toDataURL({
    format: 'png',
    multiplier: 2        
  });
  console.log(data);
  //var img = document.getElementById('export');//img.src = data;
}, false);

var clipRect1 = new fabric.Rect({
    originX: 'left',
    originY: 'top',
    angle: 90,
    left: 195,
    top: 0,
    width: 200,
    height: 200,
    fill: '#DDD', /* use transparent for no fill */strokeWidth: 1,
    lockMovementX: true,
    lockMovementY: true,
    stroke: 'red',
    angle: 5
});



var pugImg = newImage();
pugImg.onload = function (img) {    
    var pug = new fabric.Image(pugImg, {
        angle: 0,
        width: 500,
        height: 500,
        left: 245,
        top: 35,
        scaleX: 0.3,
        scaleY: 0.3,
        clipName: 'pug',
        clipTo: function(ctx) { 
            ctx.save();
            var myMatrix = this.calcTransformMatrix();
            myMatrix = fabric.util.invertTransform(myMatrix);
            ctx.transform.apply(ctx, myMatrix);
            clipRect1.render(ctx);
            ctx.restore();
        }
    });
    canvas.add(pug);
};
pugImg.src = img02URL;
#c {
    border:0px solid #ccc;
}
<scriptsrc="//www.deltalink.it/andreab/fabric/fabric.js"></script><canvasid="c"width="500"height="400"></canvas><aid="download">Download as image</a><imgid="export" >

Post a Comment for "Fabric Todataurl With Multiplier Not Working As Expected"