Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric JS html 5 image curving options

I want to make image curve with html5 tool.

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

Please guide me on how to make curved image on image like mug, glass, cylindrical or circular type of products.

Ref. image is below:

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

like image 859
ashishbhattb Avatar asked Mar 18 '23 04:03

ashishbhattb


1 Answers

What you are desiring is called 'perspective warping' and is not available in native 2D canvas.

You can achieve your effect by drawing 1 pixel wide vertical strips of your image with the appropriate Y-offsets.

enter image description here

Here's an outline of how to do it to give you a starting point:

  • Create an array of y-offsets that form your desired curve:

    // 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];
    
  • Create an in-memory canvas:

    var canvas=document.createElement('canvas')
    var context=canvas.getContext('2d');
    
  • Use the clipping version of context.drawImage to draw 1 pixel wide vertical slices of the image with "curving" y-offsets:

    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
        );           
    }
    
  • Create an image from the temporary canvas and create an image object in 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();
    
like image 131
markE Avatar answered Mar 20 '23 18:03

markE