Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I get this HTML5 Canvas paint application to work for both touch and mouse events?
    text
    copied!<p>Here is the source code of what I'm trying to do:</p> <p><a href="http://jsfiddle.net/3nGtM/" rel="nofollow">http://jsfiddle.net/3nGtM/</a></p> <p>Javascript:</p> <pre><code> window.addEventListener('load', function () { // get the canvas element and its context var canvas = document.getElementById('sketchpad'); var context = canvas.getContext('2d'); // create a drawer which tracks touch movements var drawer = { isDrawing: false, touchstart: function (coors) { context.beginPath(); context.moveTo(coors.x, coors.y); this.isDrawing = true; }, touchmove: function (coors) { if (this.isDrawing) { context.lineTo(coors.x, coors.y); context.stroke(); } }, touchend: function (coors) { if (this.isDrawing) { this.touchmove(coors); this.isDrawing = false; } } }; // create a function to pass touch events and coordinates to drawer function draw(event) { // get the touch coordinates var coors = { x: event.targetTouches[0].pageX, y: event.targetTouches[0].pageY }; // pass the coordinates to the appropriate handler drawer[event.type](coors); } // attach the touchstart, touchmove, touchend event listeners. canvas.addEventListener('touchstart', draw, false); canvas.addEventListener('touchmove', draw, false); canvas.addEventListener('touchend', draw, false); // prevent elastic scrolling document.body.addEventListener('touchmove', function (event) { event.preventDefault(); }, false); // end body.onTouchMove }, false); // end window.onLoad </code></pre> <p>HTML:</p> <pre><code>&lt;body&gt; &lt;div id="container"&gt; &lt;canvas id="sketchpad" width="400" height="400"&gt;Sorry, your browser is not supported.&lt;/canvas&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>CSS:</p> <pre><code>body { margin:0; padding:0; font-family:Arial; } #container { position:relative; } #sketchpad { border: 1px solid #000; } </code></pre> <p>I tried adding event listeners for mouse down/up/move but those didn't seem to work. </p> <p>Alternatively, if anyone has any suggestions for open source canvas painting apps that work on computer and tablet I'd rather just use that.</p> <p>So far the only one that has stood out is <a href="https://github.com/PlayMyCode/SkyBrush" rel="nofollow">https://github.com/PlayMyCode/SkyBrush</a> but it unfortunately doesn't work on android tablets (at least the ones I've been able to try).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload