Search code examples
javascripthtmlcanvashtml5-canvas

HTML5 canvas, image on/in polygon possible?


Is there a way using javascript html5 canvas, to have a polygon and then display an image in it instead of a color?


Solution

  • After some research, I believe it's possible to do that by first creating a pattern using your image, then setting that pattern to fillStyle:

    var ctx = canvas.getContext("2d");
    var pattern = ctx.createPattern(imageObj, "repeat");
    ctx.fillStyle = pattern;
    

    Then it's just a matter of creating your polygon (using moveTo and lineTo) and then filling it normally.

    Source: this plugin's source code. Disclaimer: haven't tried it myself to confirm that works.

    Update: I'm still investigating whether or not you can manipulate the image to fit an arbitrary polygon. In principle, you could use setTransform to do that:

    ctx.save();
    ctx.setTransform(m11, m12, m21, m22, dx, dy);
    ctx.drawImage(imageObj);
    ctx.restore();
    

    Determining the values of setTransform parameters (if it's possible to do that at all) is the tricky part. It's been looong since I did any math, but if I recall correctly here's what needs to be done:

    (0,0) --- (w,0)       (x1,y1) --- (x2,y2)
      |         |            |           |
      |  Image  |     =>     |  Morphed  |
      |         |            |           |
    (0,h) --- (w,h)       (x3,y3) --- (x4,y4)
    

    For each point, you'd do the following matrix operation:

    |m11 m21 dx|   |xI|   |xM|
    |m12 m22 dy| X |yI| = |yM|
    | 0   0   1|   | 1|   | 1|
    

    Eight equations, six variables (remembering that the matrix elements are the variables, the rest are constants - our inputs). Might be unsolvable. Now it's only a matter of deducing (or googling, or asking in Math.SE...) and implementing the formulas for each parameter...

    Update 2: Although I don't have hard evidence of that, I believe it's impossible to do what you want with setTransform. Looking at how Gimp does with its "perspective" tool, it's necessary to change also the third row of the transform matrix to transform your image to an arbitrary polygon. And the Canvas API does not seem to provide means for that (usually only affine transformations are supported: translation, rotation, scale, shear or a combination of above).

    Quoting this post on 2D transforms:

    CSS3 2D-Transforms can only transform blocks into parallelograms. For example, it is impossible to transform a block into this shape: [Irregular Shape] In order to do this, one must use CSS3 3D Transforms. This is why the Matrix Construction Set only has three control points to drag around, not four.

    There are plans for CSS 3D Transforms, but not only I don't know how widely supported that is, I dunno if the canvas element (with 2d context, that is - WebGL is another story) will ever support it. In short, it's not possible to do what you want through any means I know of.