Widget Wednesdays #21

Continuing the theme from yesterday of “simple is good”, today I’m going to talk about the concept of “hello world”. As most programmers know, one of the first programs you ever implement when you learn to program is one that just prints out the phrase “hello world”.

The idea is that you want to start programming something very simple, and then — once you’ve gotten your first program working — build from there. The nice thing about a “hello world” program is that it is very short and easy to write.

For example, in Javascript (the native language of the Web) a “hello world” program looks like this:

      console.log(‘hello world’);

It doesn’t get much simpler than that. Which got me wondering, what is a “hello world” program for interactive computer graphics on the Web?

So today I implemented one, which you can run here. All it does is let you move around a black square against a white background.

It works whether you are on a computer or a SmartPhone. The entire program file consists of 13 lines:

<center><canvas id=C width=1280 height=800></canvas>
let c = C.getContext('2d'), r = C.getBoundingClientRect(),
    w = C.width, h = C.height, p = [w/2, h/2],
    s = (u,v) => p = [u - r.left, v - r.top];
C.addEventListener('mousemove', e => s(e.x, e.y));
C.addEventListener('touchmove', e => s(e.changedTouches[0].pageX,
setInterval(() => {
   c.fillStyle = 'white'; c.fillRect(0, 0, w, h);
   c.fillStyle = 'black'; c.fillRect(p[0]-50, p[1]-50, 100, 100);
}, 30);

If you want to program interactive computer graphics for the Web, you can start with something this simple. From there you can keep building and building, and eventually create worlds of your own.

Leave a Reply