I am using the sketch.js
plugin for drawing on HTML5 canvas. While it works fine on desktop computers it seems to have some issues on mobile browsers.
The problem is that if I draw 2 different shapes, the canvas will reset to blank as soon as I touch it.
Just to be completly clear I will make and example: drawing the number '12' will first draw '1' and then when I start drawing '2' the canvas will clear and only keep the number '2'...
<!-- CANVAS -->
<canvas id="canvas1" style="width:100%; background:white; height:150px;"></canvas>
<script type="text/javascript">
$(function () {
$('#canvas1').sketch();
});
</script>
This is it. I am wondering if there is some workaround to keep the history of the various drawings. I am open to any suggestion or to know if you have found a similar problem.
To actually fix this bug, you need to change a few different lines of code. The plugin is checking during each event if the user is using a desktop (mousedown, mousemove, mouseleave, mouseup) or a mobile (touchstart, touchend, touchcancel). To determine the mouse/finger position to draw the next point, jQuery's e.pageX
is being called. This is directly defined in mobile, so the plugin is checking for mobile and if mobile is detected, saving the user's finger position defined by e.originalEvent.targetTouches[0].pageX
. The problem comes from touchend or touchcancel because e.originalEvent.targetTouches[0]
is not defined for these two events, so e.originalEvent.targetTouches[0].pageX
returns an error and the entire canvas is redrawn. To fix this, you need to edit 2 lines of code around line 100/101.
Replace
e.pageX = e.originalEvent.targetTouches[0].pageX;
e.pageY = e.originalEvent.targetTouches[0].pageY;
With
if (e.originalEvent.targetTouches[0] !== undefined && e.originalEvent.targetTouches[0].pageX!==undefined){
e.pageX = e.originalEvent.targetTouches[0].pageX;
}
if (e.originalEvent.targetTouches[0] !== undefined &&e.originalEvent.targetTouches[0].pageY){
e.pageY = e.originalEvent.targetTouches[0].pageY;
}
See the answer below for more details.
Sketch.js pageX undefined error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With