Canvas bezier curves
The new Christmas design for this site uses bezier curves on canvas elements to generate random snowdrifts behind the header. Drawing a bezier curve is pretty simple, so seems like a reasonable place to start my new blog. First you need a canvas and a context:
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext("2d");
;
</script>
The canvas bezier curve takes 6 arguments; two sets of control points, and an end point:
context.bezierCurveTo(c1x, c1y, c2x, c2y, ex, ey);
Here's an example:
context.beginPath();
context.moveTo(50, 50);
context.bezierCurveTo(50, 150, 250, 150, 350, 50);
context.strokeStyle = '#00d';
context.stroke();
I've added some grey lines and red markers to show what's going on. First we moveTo(50, 50)
, then call bezierCurveTo
with the two control points (50, 150)
and (250, 150)
, and the end point (350, 50)
. The result is a line from the current position to the end point, pulled out of place by the control points.
Once you've got that far, building a randomly-generated snowdrift is trivial - a bit of Math.random()
, and instead of context.stroke()
use context.fillStyle
and context.fill()
.
To finish the effect, I'm drawing two background snowdrifts on one canvas element, and a foreground snowdrift on a second, with snowflakes falling in between - although I cheated there and used an animated gif which I had rendered earlier. Your CPU thanks me.
Leave a comment
- Add a comment - it's quick, easy and anonymous