Slow Javascript touch events on Android
- by oneself
I'm trying to write a simple html based drawing application (standalone simplified code attached bellow). I've tested this on the following devices:
iPad 1 and 2: Works great
ASUS T101 running Windows: Works great
Samsung Galaxy Tab: Extremely slow and patchy -- unusable.
Lenovo IdeaPad K1: Extremely slow and patchy -- unusable.
Asus Transformer Prime: Noticeable lag compare with the iPad -- close to usable.
The Asus tablet is running ICS, the other android tablets are running 3.1 and 3.2. I tested using the stock Android browser. I also tried the Android Chrome Beta, but that was even worse.
My questions is why are the Android tablets so slow? Am I doing something wrong or is it an inherit problem with Android OS or browser, or is there anything I can do about it in my code?
multi.html:
<html>
<body>
<style media="screen">
canvas { border: 1px solid #CCC; }
</style>
<canvas style="" id="draw" height="450" width="922"></canvas>
<script class="jsbin" src="jquery.js"></script>
<script src="multi.js"></script>
</body>
</html>
multi.js:
var CanvasDrawr = function(options) {
// grab canvas element
var canvas = document.getElementById(options.id),
ctxt = canvas.getContext("2d");
canvas.style.width = '100%'
canvas.width = canvas.offsetWidth;
canvas.style.width = '';
// set props from options, but the defaults are for the cool kids
ctxt.lineWidth = options.size || Math.ceil(Math.random() * 35);
ctxt.lineCap = options.lineCap || "round";
ctxt.pX = undefined;
ctxt.pY = undefined;
var lines = [,,];
var offset = $(canvas).offset();
var eventCount = 0;
var self = {
// Bind click events
init: function() {
// Set pX and pY from first click
canvas.addEventListener('touchstart', self.preDraw, false);
canvas.addEventListener('touchmove', self.draw, false);
},
preDraw: function(event) {
$.each(event.touches, function(i, touch) {
var id = touch.identifier;
lines[id] = { x : this.pageX - offset.left,
y : this.pageY - offset.top,
color : 'black'
};
});
event.preventDefault();
},
draw: function(event) {
var e = event, hmm = {};
eventCount += 1;
$.each(event.touches, function(i, touch) {
var id = touch.identifier,
moveX = this.pageX - offset.left - lines[id].x,
moveY = this.pageY - offset.top - lines[id].y;
var ret = self.move(id, moveX, moveY);
lines[id].x = ret.x;
lines[id].y = ret.y;
});
event.preventDefault();
},
move: function(i, changeX, changeY) {
ctxt.strokeStyle = lines[i].color;
ctxt.beginPath();
ctxt.moveTo(lines[i].x, lines[i].y);
ctxt.lineTo(lines[i].x + changeX, lines[i].y + changeY);
ctxt.stroke();
ctxt.closePath();
return { x: lines[i].x + changeX, y: lines[i].y + changeY };
},
};
return self.init();
};
$(function(){
var drawr = new CanvasDrawr({ id: "draw", size: 5 });
});