1

I want to draw an image in trapezium shape using canvas.

I tried with the transform but i am not getting the trapezium view.

Please anyone give me the solution to draw the image in trapezium view using canvas.

I want the actual image should be transformed like this /_\

user1275353
  • 65
  • 3
  • 6
  • So, just to be sure, you want an actual image to be transformed, and drawn on the canvas? So the image'll be shaped something like /_\ that? – Cerbrus May 13 '14 at 06:37
  • hope this helps http://www.subshell.com/en/subshell/blog/image-manipulation-html5-canvas102.html – Manish Gautam May 13 '14 at 06:48

1 Answers1

4

Here is how you can "transform" an image into a trapezoid shape. The technique is well-known slicing the image line for line and drawing the line scaled a little by little.

This function allows you set amount (%) of trapezoid shape and handles scaled image as well:

function drawTrapezoid(ctx, img, x, y, w, h, factor) {

    var startPoint = x + w * 0.5 * (factor*0.01), // calculate top x
        xi, yi, scale = img.height / h,           // used for interpolation/scale
        startLine = y,                            // used for interpolation
        endLine = y + h;                          // abs. end line (y)

    for(; y < endLine; y++) {

        // get x position based on line (y)
        xi = interpolate(startPoint, y, x, endLine, (y - startLine) / h);

        // get scaled y position for source image
        yi = (y * scale + 0.5)|0;

        // draw the slice
        ctx.drawImage(img, 0, yi, img.width, 1,       // source line
                           xi.x, y, w - xi.x * 2, 1); // output line
    }

    // sub-function doing the interpolation        
    function interpolate(x1, y1, x2, y2, t) {
        return {
            x: x1 + (x2 - x1) * t,
            y: y1 + (y2 - y1) * t
        };
    }
}

FIDDLE

Snap

Hope this helps!

  • +1, Good job as always :-) I was too tired last night to code an example. BTW, is that your cute dog? – markE May 13 '14 at 14:59
  • 1
    Thanks @markE. ah no, it's just a random imgur pic. :) –  May 13 '14 at 22:53
  • 1
    This is great!!! Is there a way to modify this to draw image by giving the four corner points? – Janaka Jul 27 '17 at 07:09
  • @Janaka not natively, but you can implement it manually like here: https://stackoverflow.com/a/36381584/1693593 –  Jul 28 '17 at 11:45