Fabric JS html 5 image curving options

早过忘川 提交于 2019-12-04 11:01:58

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.

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();
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!