Is there a way using javascript html5 canvas, to have a polygon and then display an image in it instead of a color?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:Then it’s just a matter of creating your polygon (using
moveToandlineTo) 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
setTransformto do that:Determining the values of
setTransformparameters (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:For each point, you’d do the following matrix operation:
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:
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.