Hosting Solutions
mobile_logo Table of Contents
seal_frontseal_back

Detect Mouse Coordinates on Canvas

In this exercise we are going to cover one of the most crucial aspects of making interactive canvas applications with JavaScript. We will demonstrate how to read or capture the user mouse coordinates upon specific events. <!DOCTYPE html> <html> <head> <style> body{ margin:10px; background:#CCC; } #my_canvas{ background:#FFF; border:#000 1px solid; } </style> <script> function initCanvas(){ var ctx = document.getElementById('my_canvas').getContext('2d'); ctx.canvas.addEventListener('mousemove', function(event){ var mouseX = event.clientX - ctx.canvas.offsetLeft; var mouseY = event.clientY - ctx.canvas.offsetTop; var status = document.getElementById('status'); status.innerHTML = mouseX+" | "+mouseY; }); ctx.canvas.addEventListener('click', function(event){ var mouseX = event.clientX - ctx.canvas.offsetLeft; var mouseY = event.clientY - ctx.canvas.offsetTop; // alert(mouseX+" | "+mouseY); ctx.fillStyle = "orange"; ctx.fillRect(mouseX-15, mouseY-15, 30, 30); }); } window.addEventListener('load', function(event) { initCanvas(); }); </script> </head> <body> <canvas id="my_canvas" width="500" height="300"></canvas> <h2 id="status">0 | 0</h2> </body> </html>
thumb

JavaScript Videos

Canvas Programming

2D Context Object and Rectangle MethodsFill and Stroke Styles Color Gradient PatternLine Styles for Lines and StrokesBuilding and Drawing PathsDrawing Images and VideosDrawing Text on CanvasRendering Shadows on CanvasCanvas Transformation EffectsPixel Manipulation on CanvasCompositing on the CanvasDynamic Centering and Alignment on the CanvasCanvas Animation and App InitializationObject Oriented Assets OOP on CanvasDetect Mouse Coordinates on CanvasAnimated Background Layers on Canvas TutorialKeyboard Control and MovementJSON Object Arrays and Loops on CanvasHit Detection Mouse Touch Over Object ArraysCollision Detection Hit Game EnemiesParticle Effect System Tutorial Snow Falling AnimationInteractive Canvas Imaging Applications JavaScript PHP TutorialCircular Progress Loader Canvas JavaScript Programming Tutorial