JavaScript Day 24: Curves

Mar 24 2011 Published by under JavaScript

Send to Kindle

Just playing around with some generative type drawing today, using curves.

In Flash, you have moveTo and curveTo. In JavaScript, you have the exact two functions that work exactly the same way, creating a quadratic curve. But you also have bezierCurveTo, which is a nice addition.

To make a quadratic curve, moveTo a certain point, then call quadraticCurveTo(controlPointX, controlPointY, endPointX, endPointY) just like in Flash’s curveTo.

context.beginPath();
context.moveTo(100, 100);
context.quadraticCurveTo(200, 0, 300, 100);
context.stroke();

I’m not going to beat that one to death. You get it.

The bezierCurveTo function works the same way, but you get two control points, so you can make a more complex curve.

context.beginPath();
context.moveTo(100, 100);
context.bezierCurveTo(200, 0, 400, 300, 300, 100);
context.stroke();

That’s all there is to it really, but you can do some cool stuff like this:

Here’s the code for that:

$(function () {
    var i, j, canvas, context, points = [], width, height, numLines = 10;
    
    canvas = $("#canvas")[0];
    context = canvas.getContext("2d");
    width = canvas.width;
    height = canvas.height;
    context.lineWidth = 0.1;
    
    for(i = 0; i < 4 * numLines; i += 1) {
        points.push({x:Math.random() * width, y:Math.random() * height, vx:Math.random() * 4 - 2, vy:Math.random() * 4 - 2});
    }
    
    setInterval(function() {
        for(j = 0; j < numLines; j += 1) {
            context.beginPath();
            context.moveTo(points[j * 4].x, points[j * 4].y);
            context.bezierCurveTo(points[j * 4 + 1].x, points[j * 4 + 1].y,
                                  points[j * 4 + 2].x, points[j * 4 + 2].y,
                                  points[j * 4 + 3].x, points[j * 4 + 3].y);
            context.stroke();
        }
        for(i = 0; i < points.length; i += 1) {
            points[i].x += points[i].vx;
            points[i].y += points[i].vy;
        }
    }, 1000/24);
});

Basically, I create an array of points. Four random points for each line. Each point has a random x, y and a random vx, vy for velocity.

On each frame, I move to a point and then draw a curve through the next three points, and so on for each curve. Then I update all the points by adding the velocity to the position. Each line is drawn with a width of 0.1, so the many lines build up over time into a neat texture.

See it in action here: http://www.bit-101.com/jscanvas/mar24.html. Refresh to get a new design.

Send to Kindle

8 responses so far. Comments will be closed after post is one year old.