0

I have the following code for a simple html5 canvas drawing app (code from here). However, I can't get the canvas to draw on mouse down. Any ideas?

Tried this in Firefox, not IE.

Any help appreciated.

<!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <script type="text/javascript"> var canvas = document.querySelector('#paint'); var ctx = canvas.getContext('2d'); var sketch = document.querySelector('#sketch'); var sketch_style = getComputedStyle(sketch); canvas.width = parseInt(sketch_style.getPropertyValue('width')); canvas.height = parseInt(sketch_style.getPropertyValue('height')); var mouse = {x: 0, y: 0}; var last_mouse = {x: 0, y: 0}; /* Mouse Capturing Work */ canvas.addEventListener('mousemove', function(e) { last_mouse.x = mouse.x; last_mouse.y = mouse.y; mouse.x = e.pageX - this.offsetLeft; mouse.y = e.pageY - this.offsetTop; }, false); /* Drawing on Paint App */ ctx.lineWidth = 5; ctx.lineJoin = 'round'; ctx.lineCap = 'round'; ctx.strokeStyle = 'blue'; canvas.addEventListener('mousedown', function(e) { canvas.addEventListener('mousemove', onPaint, false); }, false); canvas.addEventListener('mouseup', function() { canvas.removeEventListener('mousemove', onPaint, false); }, false); var onPaint = function() { ctx.beginPath(); ctx.moveTo(last_mouse.x, last_mouse.y); ctx.lineTo(mouse.x, mouse.y); ctx.closePath(); ctx.stroke(); }; </script> <style type="text/css"> html, body { width: 100%; height: 100%; } #sketch { border: 10px solid gray; height: 100%; } </style> </head> <body> <div id="sketch"> <canvas id="paint"></canvas> </div> </body> </html> 
0

1 Answer 1

2

The problem is that you're trying to access a tag (var canvas = document.querySelector('#paint'); ) while it has not yet been loaded.

Put your whole JavaScript tag after the tag of </canvas>.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.