Fabric JS html 5 image bending options

I want to create image graphics using the html5 tool.

I am using Fabric.js for the html5 canvas tool.

Tell us how to make a curved image in the image, for example, with a mug, glass, a cylindrical or round type of product.

Ref. image below:

http://vsdemo.cwwws.com/Images/ProductImages/asdasd.jpg

+4
source share
1 answer

What you want is called “perspective warping” and is not available in your own 2D canvas.

You can achieve your effect by drawing vertical stripes 1 pixel wide of your image with corresponding Y offsets.

enter image description here

, , :

  • y-, :

    // Just an example, you would define much better y-offsets!
    // Hint: Better offsets can be had by fetching y-values from a quadratic curve.
    
    var yOffsets=[0,1,2,3,4,5,6,5,4,3,2,1,0];
    
  • :

    var canvas=document.createElement('canvas')
    var context=canvas.getContext('2d');
    
  • context.drawImage, 1 "" y-:

    for(var x=0;x<offsetY.length;x++){
        context.drawImage(img,
            // clip 1 pixel wide slice from the image
            x,0,1,img.height,
            // draw that slice with a y-offset
            x,offsetY[x],1,img.height
        );           
    }
    
  • FabricJS:

    var perspectiveImage=new Image();
    perspectiveImage.onload=function(){
        // This is the mug-shaped image you wanted! 
        // Use it in FabricJS as desired.
    }
    perspectiveImage.src=canvas.toDataURL();
    
+7