Draw

Draw.html  [download]

<!DOCTYPE html>

<html>
<head>

<title>Comp 86 example Draw</title>
<!-- Similar to java Draw3, using HTML5 canvas -->

<script type="text/javascript">

function doit (event) { //*1 Callback when canvas is clicked
	// Show coordinates
	document.getElementById("showcoords").innerHTML = //*2 Display the coordinates, by patching HTML
		"Mouse down at " + event.clientX + ", " + event.clientY; //*2
             
	// Redraw, moving the red circle to match mouse location
	drawBackground (); //*3 Common code to redraw my background
	var c = document.getElementById ("MyCanvas"); //*4 Find my canvas in the HTML
	var gc = c.getContext("2d");
	gc.fillStyle = "#FF0000"; //*5 Draw red circle at mouse location
	gc.beginPath(); //*5
	gc.arc (event.clientX, event.clientY, 20, 0, 2.*Math.PI); //*5
	gc.fill(); //*5
}

// Just a common code fragment, not a genuine repaint callback,
// redraws the non-changeable stuff
function drawBackground () { //*3
	var c = document.getElementById ("MyCanvas"); //*3
	var gc = c.getContext("2d"); //*3

	// Grey background
	gc.fillStyle = "#EEEEEE"; //*3
	gc.fillRect (0, 0, c.width, c.height); //*3

	// Same line as in the java version
	gc.strokeStyle = "black" //*3
	gc.beginPath(); //*3
	gc.moveTo (50, 50); //*3
	gc.lineTo (100, 50); //*3
	gc.stroke(); //*3
}

window.onload = drawBackground //*3

</script> 
</head>

<body>

<canvas id="MyCanvas" width="300" height="300" onmousedown="doit(event)"></canvas>

<p><span id="showcoords"></span></p>

</body>
</html>