HTML
Add html tag and add canvas element.
<canvas id=”pad” width=”1366″ height=”271″>
<p>Not Supported</p>
</canvas>
html, body { width: 100%; height: 100%; margin: 0px; }
isMobile: variable detects the current browser is support touch events or not because when we want the current position of browser in touch screen devices we can get it from event.targetTouches[0].pageX and event.targetTouches[0].pageY. However in normal browsers we can calculate by event.pageX – this.offsetLeft and event.pageY – this.offsetRight.
There is also different events on touch enabled devices, when you start drawing on browser it fires touchStart event where as the browser fire mouseDown event.
please follow the table for equivalent event on browser and touch enable browser.
Browser: mouseDown, mouseMove, mouseUp
Mobile devices: touchStart, touchMove, touchEnd
click here for Demo
var isMobile; function isTouchDevice() { var el = document.createElement('div'); el.setAttribute('ongesturestart', 'return;'); return typeof el.ongesturestart === "function"; } isMobile = isTouchDevice(); if(window.addEventListener) { window.addEventListener('load', function () { var canvas, context, draw; // Touch Events handlers draw = { started: false, start: function(event) { context.beginPath(); if (isMobile){ context.moveTo( event.targetTouches[0].pageX, event.targetTouches[0].pageY ); }else{ context.moveTo( event.pageX - this.offsetLeft, event.pageY - this.offsetTop ); } this.started = true; }, move: function(event) { if (this.started) { if(isMobile){ context.lineTo( event.targetTouches[0].pageX, event.targetTouches[0].pageY ); }else{ context.lineTo( event.pageX - this.offsetLeft, event.pageY - this.offsetTop ); } context.stroke(); } }, end: function(event) { this.started = false; } }; // Canvas & Context canvas = document.getElementById('pad'); context = canvas.getContext('2d'); // Full Window Size Canvas context.canvas.width = window.innerWidth; context.canvas.height = window.innerHeight; // Events canvas.addEventListener('touchstart', draw.start, false); canvas.addEventListener('touchend', draw.end, false); canvas.addEventListener('touchmove', draw.move, false); canvas.addEventListener('mousedown', draw.start, false); canvas.addEventListener('mousemove', draw.move, false); canvas.addEventListener('mouseup', draw.end, false); }); // Disable Page Move document.body.addEventListener('touchmove',function(event){ event.preventDefault(); },false); }
There is also another way to create drawing board on canvas, by printing images on the mouse movement.
check out this example Click here for Demo