Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR HTML

js get mouse position canvas

<canvas id="canvas" onmousemove="onMouseMove(event)"></canvas>
<script>
  	let canvas = document.getElementById("canvas");
  
	function onMouseMove(evt) {
    	let mousePos = getMousePos(evt);
		console.log("Mouse X : " + mousePos.x + ", Mouse Y : " + mousePos.y);
    }

	function getMousePos(evt) {
		let rect = canvas.getBoundingClientRect();
		return {
			x: evt.clientX - rect.left,
			y: evt.clientY - rect.top
		};
	}
</script>
 
PREVIOUS NEXT
Tagged: #js #mouse #position #canvas
ADD COMMENT
Topic
Name
8+5 =