Mouse Position in HTML 5 Canvas

I am writing a simple drawing application to get an idea of ​​HTML 5 canvas. The problem is that I just cannot get the right mouse position in the canvas element. I looked at other stackoverflow questions, like here, to get javascript mouse position within the canvas , which solve this problem, but their solutions don't seem to help me.

Here is my code:

<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Untitled Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> <style type="text/css"> #test { border: solid black 1px; width: 500px; height: 500px; } </style> <script type="text/javascript"> $(function(){ var canvas=document.getElementById('test'); if(canvas.getContext){ var ctx =canvas.getContext('2d'); var draw = false; ctx.strokeStyle = "rgb(200,0,0)"; ctx.lineWidth = 3; ctx.lineCap = "round"; $('#test').mousedown(function(){draw=true;}); $('#test').mouseup(function(){draw=false;}); $('#test').mousemove(function(e){ if(draw){ var x , y; x = e.layerX; y = e.layerY; ctx.moveTo(x,y); ctx.lineTo(x+1,y+1); ctx.stroke(); } }); } }); </script> </head> <body> <canvas id="test"></canvas> </body> </html> 

What am I doing wrong here? I tested it like in Chrome / Firefox.

+4
javascript html5 canvas
Feb 06 '11 at 18:47
source share
3 answers

Your canvas lacks width and height properties. In the current solution, it simply scales the default value to suit your CSS. This in turn breaks your mice. Try something by

 <canvas id="test" width=500 height=500></canvas> 

as a markup of your canvas.

+5
Feb 06 '11 at 18:58
source share

Suppose your canvas is already declared ...

 var Mouse = { //make a globally available object with x,y attributes x: 0, y: 0 } canvas.onmousemove = function (event) { // this object refers to canvas object Mouse = { x: event.pageX - this.offsetLeft, y: event.pageY - this.offsetTop } } 

The mouse will update when you move the mouse on the canvas.

+3
Feb 06 2018-11-11T00:
source share

You must add the pixel size to your canvas element:

 <canvas id="test" width='500px' height='500px' ></canvas> 

Here is a working example - http://jsfiddle.net/gorsky/GhyPr/ .

+2
Feb 06 '11 at 19:15
source share



All Articles