Frederic Cambus

Home · Archives · Text Mode · GitHub · Twitter · RSS

JavaScript Canvas Element and JS1k Contest

· JavaScript

I've been experimenting with JavaScript and the canvas element lately, something I wanted to do since a long time, and I must say it's quite fun to play with. As a result, I submited a modest 322 bytes entry for JS1k (1k Javascript demo contest), which is a visual representation of a stripped-down bubble sort algorithm producing diagonal lines pattern.

You can see it in action here: http://js1k.com/demo/503

The code is embedded below:

M=Math;var n=128,s=768;a=[];for(l=0;l<n;l++)a[l]=M.floor(M.random()*n);g=document.getElementById("c");g.width=g.height=s;c=g.getContext("2d");setInterval("for(i=0;i<n;i++)if(a[i]<a[i+1]){b=a[i];a[i]=a[i+1];a[i+1]=b;}c.clearRect(0,0,s,s);for(i=0;i<n;i++)for(j=0;j<6;j++)for(k=0;k<5;k++)c.fillRect(j*n+i,k*n+a[i],6,6);",25);

The contest is running until September 10th so should you be interested, I recommend the Canvas tutorial at Mozilla Developer Network and the Closure Compiler to help you minimize your JavaScript code. Good luck everyone, and have fun!