<!DOCTYPE html> <html> <head> <title>Comp 86 example Draw</title> <!-- Similar to java Draw3, using HTML5 canvas --> <script> function doit (event) { //*1 Callback when canvas is clicked // Show coordinates showcoords.textContent = //*2 Display the coordinates, by patching HTML "Mouse down at " + event.clientX + ", " + event.clientY; //*2 // Correct the mouse coordinates for location of canvas within window let bounds = myCanvas.getBoundingClientRect(); //*6 Correct the mouse coordinates let newx = Math.floor (event.clientX - bounds.left); //*6 let newy = Math.floor (event.clientY - bounds.top); //*6 showcoords.textContent += " - Corrected to " + newx + ", " + newy; // Redraw, moving the red circle to match corrected mouse location drawBackground (); //*3 Common code to redraw my background let gc = myCanvas.getContext("2d"); //*4 Find my canvas in the HTML gc.fillStyle = "#FF0000"; //*5 Draw red circle at mouse location gc.beginPath(); //*5 gc.arc (newx, newy, 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 let gc = myCanvas.getContext("2d"); //*3 // Grey background gc.fillStyle = "#EEEEEE"; //*3 gc.fillRect (0, 0, myCanvas.width, myCanvas.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>