I'm trying to create a site that curves an image uploaded by a user, and then allows the user to save the new image. I'm having trouble figuring out how to curve the image as shown in the link below. I can create the curved shape as a solid color in Canvas, but not with an image.
http://i53.tinypic.com/2gule04.jpg
I tried something like this.
I have a source image having width 300 and height 227. And I am going to bend this image 15 pixel down. So create a canvas with same width and height = imageWidth + 15 px. ie. 227+15 = 242.
HTML:
<img id="source" src="rhino.jpg">
<canvas id="canvas" width="300" height="242" ></canvas>
Javascript
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = document.getElementById('source');
var x1 = img.width / 2;
var x2 = img.width;
var y1 = 15; // curve depth
var y2 = 0;
var eb = (y2*x1*x1 - y1*x2*x2) / (x2*x1*x1 - x1*x2*x2);
var ea = (y1 - eb*x1) / (x1*x1);
// variable used for the loop
var currentYOffset;
for(var x = 0; x < img.width; x++) {
// calculate the current offset
currentYOffset = (ea * x * x) + eb * x;
ctx.drawImage(img,x,0,1,img.height,x,currentYOffset,1,img.height);
}
There's no simple way to do this. You might need to code the transformation yourself using the pixelwise API of Canvas. See http://beej.us/blog/2010/02/html5s-canvas-part-ii-pixel-manipulation/ .
Instead of pure pixel based solution you could try a mesh based one. Split up the source image to smaller chunks that map to the target shape. Then use texture mapping to fill in the details. See Image manipulation and texture mapping using HTML5 Canvas? for the mapping algo. You may find another algo here. You'll still need to figure out the mapping coordinates, though.