Curving an image that starts as a rectangle (uploaded by user), preferably using Canvas or JS

坚强是说给别人听的谎言 提交于 2019-11-29 15:51:39

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);
}
Juho Vepsäläinen

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.

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