This issue has taken about four months of stress and research. I can't find a good solution for fabric v.4 +
Here's one of the solutions I learned from online: https://jsfiddle.net/naimsajjad/8w7hye2v/8/
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.3/fabric.min.js"> </script>
function ImageNew(){
let img01URL = prompt("Please enter your image URL", "https://");
fabric.Image.fromURL(img01URL, function(oImg) {
oImg.scale(.25);
oImg.left = 10;
oImg.top = 10;
oImg.clipPath = canvas.getActiveObject();
oImg.clipTo = function(ctx) {
clipObject(this, ctx)
}
canvas.add(oImg);
canvas.renderAll();
});
}
function clipObject(thisObj, ctx) {
if (thisObj.clipPath) {
ctx.save();
if (thisObj.clipPath.fixed) {
var retina = thisObj.canvas.getRetinaScaling();
ctx.setTransform(retina, 0, 0, retina, 0, 0);
// to handle zoom
ctx.transform.apply(ctx, thisObj.canvas.viewportTransform);
thisObj.clipPath.transform(ctx);
}
thisObj.clipPath._render(ctx);
ctx.restore();
ctx.clip();
var x = -thisObj.width / 2,
y = -thisObj.height / 2,
elementToDraw;
if (thisObj.isMoving === false && thisObj.resizeFilter && thisObj._needsResize()) {
thisObj._lastScaleX = thisObj.scaleX;
thisObj._lastScaleY = thisObj.scaleY;
thisObj.applyResizeFilters();
}
elementToDraw = thisObj._element;
elementToDraw && ctx.drawImage(elementToDraw,
0, 0, thisObj.width, thisObj.height,
x, y, thisObj.width, thisObj.height);
thisObj._stroke(ctx);
thisObj._renderStroke(ctx);
}
}
The thing is it works if I load it a 3.6 Fabric Library. But in modern versions, it doesn't work.
In my app, I load a grey colorless rectangle through JSON. And user selects that rectangle, and loads an image into it. So that the image will be cropped into the rectangle.
I've been trying quite a lot in trying to fix this. Please help me.