Canvas – Drawing Bamboo with Code

After drawing rectangles, lines, circles (arcs) and triangles, about all that’s left in the toy box is the curve. Canvas has two types of curves: quadratic and cubic; they differ only in the amount of control points used for bending the line.

Quadratic curves have two anchor points and one control point and curves in only one direction. The more complex cubic curve adds another control point and can curve in two directions.

Curves can be interwoven when drawing paths with lines and arcs, and they pick up wherever the current context point is (or from a explicit moveTo which established a new context point):

ctx.quadraticCurveTo(cpx, cpy, x, y);

where cpx and cpy is the control point and x,y is the endpoint

Playing with this:

// w = canvas.width
// h = canvas.height
ctx.clearRect(0,0,w,h);

ctx.save();
ctx.translate(w/2+15, h/2);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.quadraticCurveTo(50, -25, 100, 0);
ctx.quadraticCurveTo(37, 36, 0, 0);
ctx.fill();

//ctx.setTransform(1,0,0,1,0,0); //reset matrix 
ctx.translate(w/2-15, h/2);
ctx.scale(-1, 1); // mirror image...
ctx.beginPath();
ctx.moveTo(0,0);
ctx.quadraticCurveTo(50, -25, 100, 0);
ctx.quadraticCurveTo(37, 36, 0, 0);
ctx.fill();

ctx.restore();

The code draws two curves connected to each other (then endpoint on the second was the starting point on the first curve); the second set of curves calls scale(-1,1) before repeating the same calls again and creates a mirror image, which results:

eyes1

 

 

Using curves for eyes and leaves in the next project here’s an experiment constructing a bamboo grove. Each time the canvas is clicked it regenerates a new grove.

See the Pen Haunted Bamboo by Kentskyo (@kentskyo) on CodePen.0

 

 

 

 

Canvas – Triangles

There’s no built in function in canvas for making triangles, but since a triangle is just a particular arrangement of 3 lines it should be easy enough to construct with lineTo:

ctx.beginPath();
ctx.moveTo(150,100);
ctx.lineTo(100,200);
ctx.lineTo(200,200);
ctx.fill();

Triangle Coordinates

When using fill(), open paths are closed automatically, from the current point back to the starting point. That’s why lineTo(150,100) wasn’t necessary at the end. If stroke() is used instead of fill, however, then a call to closePath() is required.

Rather than painstakingly arranging triangles at specific coordinates on the grid, a different approach is to move coordinates via translate and draw the triangle at 0,0. Using this approach to arrange a set of 10 triangles around the center of the canvas:

ctx.clearRect(0,0, w, h);
ctx.fillStyle = "red";

// Triangle points
var t = []; 
t[0] = {x:0, y:-5};
t[1] = {x:-5, y:5};
t[2] = {x:5, y:5};

for (var deg = 0; deg < 360; deg += 36) {
    var a = radians(deg);
    var x = Math.cos(a) * 25;
    var y = Math.sin(a) * 25;
    ctx.translate(canvas.width/2+x, canvas.height/2+y);
    drawTriangle(t);
    ctx.setTransform(1,0,0,1,0,0); //reset identity matrix
} 

function drawTriangle(t) {
   ctx.beginPath();
   ctx.moveTo(t[0].x, t[0].y);
   ctx.lineTo(t[1].x, t[1].y);
   ctx.lineTo(t[2].x, t[2].y);
   ctx.fill();
}

function radians(deg) {
    return deg * Math.PI/180;
}

trianglerad

Now playing with the orientation of the triangles by adding the line:

ctx.rotate(radians(deg+90));

just before the call to drawTriangle.

Adding a scale function is a lazy way to draw multiple rings

var p = [];
p[0] = {x:0, y:-5};
p[1] = {x:-5, y:5};
p[2] = {x:5, y:5};

ctx.clearRect(0,0, w, h);
ctx.fillStyle = "red";

for (var i=0; i<4; i++) {
    drawRing(p, 25, 36, 90, i);
}


function drawRing(p, r, stepBy, rDegrees, scale) {
    r = r*scale+(scale * 15); 
    for (var deg = 0; deg < 360; deg += stepBy) {
        var a = radians(deg);
        var x = Math.cos(a) * r;
        var y = Math.sin(a) * r;
        ctx.translate(w/2+x, h/2+y);
        ctx.rotate(radians(deg+rDegrees));
        ctx.scale(scale, scale);
        drawTriangle(p);
        ctx.setTransform(1,0,0,1,0,0); //reset identity matrix
    } 
}

arrows

Combining this exploration into a project:

See the Pen Triangle Spirals by Kentskyo (@kentskyo) on CodePen.0

 

Canvas – Lines, Circles and Spirals

It’s time to branch beyond rectangles for our drawing elements. To draw a line between two points with the canvas api, using the context object:

ctx.strokeStyle = "red";
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stroke();

beginPath starts recording a path. Like Illustrator and some other drawing applications a path is just a set of points it doesn’t become an actual line or shape until a stroke or fill is applied. The canvas can have only one path active at a time.

lineTo(x,y) draws a path from wherever the last point was positioned on the current path to the point directed by x,y in lineTo. This initial point can be set by moveTo(x,y) or it can be wherever lineTo left off in the last call. For example:

ctx.beginPath();
ctx.moveTo(canvas.width/2, canvas.height/2);
var color = randomInt(0,360);
ctx.strokeStyle = "hsl("+color+",60%,60%";
for (var i = 0; i < 10; i++) {
    ctx.lineTo(randomInt(50, canvas.width-50), randomInt(50, canvas.height-50));
}
ctx.stroke();

We had to start the path with a call to moveTo(x,y) but after that we just piggybacked on wherever lineTo(x,y) left the last end point to begin the next line.
randomlines

Circles

Rectangle is actually the only shape canvas knows how to draw. Everything else must be built from paths. A circle is created using the arc function and telling it the starting angle (in radians) is 0 and the ending is 2*PI:

arc(x,y, radius, start-angle, end-angle, anticlockwise);

ctx.beginPath();
ctx.arc(canvas.width/2, canvas.height/2, 100, 0, 2 * Math.PI, false);
ctx.fillStyle = 'red';
ctx.fill();
ctx.lineWidth = 20;
ctx.strokeStyle = '#400d12';
ctx.stroke()

2015-11-05_105722

Combining what we’ve covered so far:

function draw() {
    ctx.strokeStyle = "red";
    ctx.lineWidth = 1;

    drawCircle(canvas.width/2, canvas.height/2, 50);

    ctx.beginPath();
    ctx.moveTo(canvas.width/2, canvas.height/2);
    for (var i = 0; i < 10; i++) {
        var x = randomInt(50, canvas.width-50);
        var y = randomInt(50, canvas.height-50); 
        ctx.lineTo(x, y);
        ctx.stroke();
        drawCircle(x,y, randomInt(5,15));
    }
}


function drawCircle(x,y,r) {
    var c = randomInt(0,360);
    ctx.beginPath();
    ctx.arc(x, y, r, 0, 2 * Math.PI, false);
    ctx.fillStyle = "hsl("+c+",60%,60%";
    ctx.fill();
}

circlesandlines

Spirals

To draw a spiral we just need to draw a circle with a radius that either grows or shrinks.

var radius = 1.0;
ctx.translate(canvas.width/2, canvas.height/2);
for (var deg = 0; deg < 360*6; deg += 3) {
    var angle = deg * Math.PI/180;
    var x = Math.cos(angle) * radius;
    var y = Math.sin(angle) * radius;
    drawCircle(x,y,2);
    radius = radius + 0.2;
}

Switching the formula in the line above from:

var angle = deg * Math.PI/180;

to:

var angle = deg * 180/Math.PI;

creates this:
spiral11

Textures

Besides colors, a fillStyle for a stroke or solid fill can also be a pattern or a gradient. Patterns are loaded from images and have an option for how they are tiled across a fill via the repeat parameter:

// example from MDN
var img = new Image();
img.src = 'pattern.png';
img.onload = function() {
    var pattern = ctx.createPattern(img, 'repeat');
    ctx.fillStyle = pattern;
    ctx.fillRect(0,0,400,400);
};

Combining patterns with spirals was the focus of the next experiment

See the Pen Textured Spirals by Kentskyo (@kentskyo) on CodePen.0