I’ve been working on developing a video game and have recently been working on incorporating touchscreen capabilities into the program. However, I noticed that the touch event tends to cause movement in the canvas to freeze.
Here is some code that I wrote up to demonstrate this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<canvas id="cnvs" width="400" height="400"></canvas>
<script>
var canvas, canvasContext;
var x = 0, y = 30;
var incrementor = 1;
window.onload = function() {
canvas = document.getElementById('cnvs');
canvasContext = canvas.getContext('2d');
colorRect(0, 0, canvas.width, canvas.height, 'white');
setInterval(updateAll, 1);
canvas.addEventListener('touchstart', touchStart);
canvas.addEventListener('touchend', touchEnd);
}
function touchStart(e) {
console.log(e);
}
function touchEnd(e) {
console.log(e);
}
function colorRect(p,a,i,n,t) {
canvasContext.fillStyle = t;
canvasContext.fillRect(p,a,i,n);
}
function updateAll() {
moveAll();
drawAll();
}
function moveAll() {
x += incrementor;
if(x > canvas.width - 20 || x < 0) {
incrementor = incrementor * -1;
}
}
function drawAll() {
colorRect(0, 0, canvas.width, canvas.height, 'black');
colorRect(x, y, 20, 20, 'red');
}
</script>
</body>
</html>
Notice that when you touch the canvas using a device with a touchscreen that the program seems to “stutter” a little bit. It’s not necessarily that there are errors that appear. In fact, the program runs through without any errors. The only “bug” that appears is that movement on the canvas tends to freeze when the touch event is called.
The main question I have is this: how to I write a program similar to this one that performs the exact same tasks, but without freezing the program in the process? I do not have any experience with jQuery or any other fancy JS plugins, so a way to do it using plain JavaScript would be helpful to my cause.