Christian Heilmann

Posts Tagged ‘silly’

A web in HTML5 canvas

Tuesday, February 21st, 2012

Whenever there is an open forum to discuss HTML5, you get very interesting questions. Sometimes you also get ones you just facepalm to. One of them was yesterday on Facebook where someone wanted a “simple web in HTML5”. As I was bored watching “revenge of the sith” I thought I give it a go. So here you go – a simple web in HTML5 canvas.

How is this done? Pretty simple actually, I just define one segment of the web in canvas:

var c = document.createElement( 'canvas' ),
    cx = c.getContext( '2d' ),
    angle = 0;
document.body.appendChild( c );
c.width = c.height = 400;
cx.lineWidth = 3;
cx.translate( 200, 200 );
cx.moveTo( 0, 0 );
cx.lineTo( -30, -200 );
cx.quadraticCurveTo( 0, -170, 30, -200 )
cx.lineTo( 0, 0 );
cx.moveTo( -25, -160 );
cx.quadraticCurveTo( 0, -140, 25, -160 )
cx.moveTo( -18, -120 );
cx.quadraticCurveTo( 0, -100, 18, -120 )
cx.moveTo( -12, -80 );
cx.quadraticCurveTo( 0, -60, 12, -80 )
cx.moveTo( -6, -40 );
cx.quadraticCurveTo( 0, -30, 6, -40 )
cx.stroke();

I translate the context of the canvas to the centre of the 400×400 pixel canvas and start painting the lines. I paint one line from 200/200 (which now is 0/0 as the translation happened) to – 30/- 200 which is the top left. I then paint a quadratic curve to the top right of the segment (30,-200) with the curve point being in between the two. I then move the canvas “pencil” to the other points on the left and draw quadratic curves to their counterparts. All of these I set with trial and error – I am sure there is a clever algo to do this, but this works.

In order to achieve the web effect all I had to do was to rotate the canvas before painting each segment. I increased the angle by 18 degrees on each iteration and rotated the canvas in radians:

var c = document.createElement( 'canvas' ),
    cx = c.getContext( '2d' ),
    angle = 0;
document.body.appendChild( c );
c.width = c.height = 400;
cx.lineWidth = 3;
cx.translate( 200, 200 );
for ( angle = 0; angle <= 360; angle += 18 ) {
  cx.save();
  cx.rotate( angle * Math.PI/180 );
  cx.moveTo( 0, 0 );
  cx.lineTo( -30, -200 );
  cx.quadraticCurveTo( 0, -170, 30, -200 )
  cx.lineTo( 0, 0 );
  cx.moveTo( -25, -160 );
  cx.quadraticCurveTo( 0, -140, 25, -160 )
  cx.moveTo( -18, -120 );
  cx.quadraticCurveTo( 0, -100, 18, -120 )
  cx.moveTo( -12, -80 );
  cx.quadraticCurveTo( 0, -60, 12, -80 )
  cx.moveTo( -6, -40 );
  cx.quadraticCurveTo( 0, -20, 6, -40 )
  cx.restore();
}
cx.stroke();

And that’s that – a web in HTML5 canvas.