Zack Stewart
Zack Stewart

Reputation: 327

Canvas fill - Diagonal Hatch

Good morning,

I'm working on a project where I need to draw generic polygons and fill them on the HTML5 Canvas. I need to fill the shapes with diagonal lines, in a configurable color. I currently see two solutions to this problem.

The first is to figure out the math and algorithm to draw colored lines over the shape itself, using moveTo and lineTo functions. While this is possible, I have no ideas how to start with the algorithm.

The second would be to use the Fill Pattern feature in the HTML5 Canvas, by creating a small PNG (say 5x5), and draw the pattern in that. I've successfully implemented this, but do not think it's possible to change the color of this image on the fly.

Has anyone worked on something similar to this? I know there are other libraries or options to use rather than the HTML5 Canvas, but we are trying to only use basic HTML/CSS/JavaScript before evaluating outside libraries.

Thank you all.

Upvotes: 1

Views: 4027

Answers (1)

Matt Styles
Matt Styles

Reputation: 2452

You can draw the pattern (using canvas) into a separate canvas element and use the DataURL methods to fill that texture into your main drawing canvas.

Pretty sure this post details the sort of thing you're after.

Upvotes: 1

Related Questions