Have a look here for some little experiments with <canvas> in HTML5.

Here is the code I produced.

Canvas Clock

$(document).ready(function(){
	function build(){
	var myC = $('#myCanvas')[0].getContext("2d");
	myC.clearRect(0,0,400,400);
	// get time 
	var d = new Date();
	var secs = d.getSeconds();
	var mins = d.getMinutes();
	var hrs = d.getHours();
	var srad = (secs * 6) * Math.PI / 180;
	var sx = 200 + Math.sin(srad) * 120;
	var sy = 200 - Math.cos(srad) * 120;
	//clock face
	myC.beginPath();
	myC.fillStyle = "#B0D9A8";
	myC.arc(200, 200, 185, 0, Math.PI*2, true); 
	myC.closePath();
	myC.fill();
	myC.beginPath();
	myC.moveTo(200, 200);
	myC.lineTo(sx, sy);
	myC.lineWidth = 2;
	myC.strokeStyle = "#83BFA3";
	myC.stroke();
	myC.closePath();
	myC.beginPath();
	myC.moveTo(200, 200);
	var mrad = (mins * 6) * Math.PI / 180;
	var mx = 200 + Math.sin(mrad) * 150;
	var my = 200 - Math.cos(mrad) * 150;
	myC.lineTo(mx, my);
	myC.lineWidth = 4;
	myC.strokeStyle = "#58B2A3";
	myC.stroke();
	myC.closePath();
	myC.beginPath();
	myC.moveTo(200, 200);
	var hrad = (hrs * 30) * Math.PI / 180;
	var hx = 200 + Math.sin(hrad) * 100;
	var hy = 200 - Math.cos(hrad) * 100;
	myC.lineTo(hx, hy);
	myC.lineWidth = 8;
	myC.strokeStyle = "#2D9993";
	myC.stroke();
	myC.save();
	myC.restore();
	}
	setInterval(build, 1000);
});

Rotating Cheese


<script language="javascript">
$(document).ready(function(){
	
	var myC = $('#myCanvas')[0].getContext("2d");
	var inc = 2;
	myC.translate(280, 180);
	
	  var cheeseSlice = function (startA, endA, col) {
		  myC.beginPath();	  
		  myC.fillStyle = col;
		  myC.arc(0,0,150,startA*Math.PI/180,endA*Math.PI/180)
		  myC.lineTo(0, 0);
		  myC.fill();
      };
	
	function build(){
		
	cheeseSlice(180, 225, "#A94D2D");
	
	cheeseSlice(225, 270, "#EE7038");
	
	cheeseSlice(270, 315, "#FBB355");
	
	cheeseSlice(315, 360, "#FFFFC8");
	
	cheeseSlice(360, 45, "#B4B48D");
	
	cheeseSlice(45, 90, "#5F93CB");
	
	cheeseSlice(90, 135, "#2B3234");
	
	cheeseSlice(135, 180, "#C0778E");
	
	myC.save();
	myC.restore();
	myC.rotate(inc * Math.PI / 180);
	
	}
  
	setInterval(build, 50);
	
	$("canvas").mousemove(function(ev){
/* 
Thanks Stack overflow
http://stackoverflow.com/questions/55677/how-do-i-get-the-coordinates-of-a-mouse-click-on-a-canvas-element
*/
			var totalOffsetX = 0;
    		var totalOffsetY = 0;
    		var canvasX = 0;
    		var canvasY = 0;
    		var currentElement = this;

    		do{
        		totalOffsetX += currentElement.offsetLeft;
    		    totalOffsetY += currentElement.offsetTop;
    		}
    		while(currentElement = currentElement.offsetParent)

    		canvasX = ev.pageX - totalOffsetX;
    		canvasY = ev.pageY - totalOffsetY;
			
			$("#x").text(canvasX);
			
			var newspeed = (280-canvasX)/280;
			inc = newspeed*-10;
			
			$("#speedx").text(newspeed);
		
	});
	
});
</script>

Inspired by reading the Canvas Tutorial on Mozilla MDN.

Leave a Comment