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:
.jpg
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./Images/ProductImages/asdasd.jpg
Share Improve this question edited Jan 16, 2015 at 23:06 kangax 39.2k13 gold badges100 silver badges135 bronze badges asked Oct 16, 2014 at 11:50 ashishbhattbashishbhattb 532 silver badges8 bronze badges 1- AFAIK there is nothing like that in the canvas API, so you will have to use getImageData and do the pixel-level manipulation yourself. – Philipp Commented Oct 17, 2014 at 13:41
2 Answers
Reset to default 7What 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();
Sorry, this does not really qualify as an answer, but my reps do not allow me to ment. Just a small addition to markE's excellent answer: perspective warping of a cylinder/circle looks like an ellipse, not a quadratic function. One method to pute y-offsets for an ellipse is:
const offsetY = (x, radiusA, radiusB) => {
return radiusB * Math.sqrt(1 - (x * x) / (radiusA * radiusA));
};
where radiusA
is half the diameter of the e.g. 'mug', and radiusB
is the maximum vertical offset. x
has to be adjusted to be '0' (zero) at the horizontal midpoint of the 'mug'.