我开发了一款需要用户输入的手机游戏,这意味着触控输入。我尝试做一个你可以在底部看到的touchevent。一段代码可以在jsfiddle上在触摸设备上运行,但是如果我将代码实现到我的覆盖代码中它就不会工作。我尝试了很多方法来解决它,但我知道了。有没有人提出要避免错误的提示?
<html>
<head>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1">
<style>
body {
margin: 0;
}
</style>
</head>
<body>
<div id= "gameArea">
<canvas id="myCanvas" ></canvas>
</div>
<script>
window.onload = window.onresize = function() {
var C = 1; // canvas width to viewport width ratio
var el = document.getElementById("myCanvas");
var viewportWidth = window.innerWidth;
var viewportHeight = window.innerHeight;
var canvasWidth = viewportWidth * C;
var canvasHeight = viewportHeight;
el.style.position = "fixed";
el.setAttribute("width", canvasWidth);
el.setAttribute("height", canvasHeight);
var x = canvasWidth / 100;
var y = canvasHeight / 100;
var ballx = canvasWidth / 100;
window.ctx = el.getContext("2d");
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// draw triangles
function init() {
recty = canvasHeight / 100 * 20;
rectx = (Math.random() *(x * 50)) + (x / 5);
rectb = (Math.random() * (x * 40)) + x * 20;
return setInterval(main_loop, 10);
}
function draw() {
rectheight = canvasHeight / 100 * 10;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// draw rect
ctx.beginPath();
fillStyle = "#000000";
ctx.rect(rectx, recty, rectb, rectheight);
ctx.fill();
// draw triangles
ctx.beginPath();
ctx.moveTo(x * 90, y * 50);
ctx.lineTo(x * 99, y * 60);
ctx.lineTo(x * 99, y * 40);
ctx.closePath();
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x * 10, y * 50);
ctx.lineTo(x * 1, y * 40);
ctx.lineTo(x * 1, y * 60);
ctx.closePath();
ctx.stroke();
// ballx
// draw ball
ctx.beginPath();
ctx.fillStyle = "#FF4422";
ctx.arc(ballx * 50, y * 50, x * 5, 0, 2 * Math.PI);
ctx.fill();
}
function update() {
recty += 1;
if (recty > canvasHeight) {
recty = -rectheight;
rectx = (Math.random() *(x * 50)) + (x / 5);
rectb = (Math.random() * (x * 50)) + x * 20;
}
if (recty > canvasHeight) {
recty -= 1;
}
}
function main_loop() {
draw();
update();
}
init();
}
function initia() {
console.log('init');
// Get a reference to our touch-sensitive element
var touchzone = document.getElementById("myCanvas");
// Add an event handler for the touchstart event
// touchzone.addEventListener("mousedown", touchHandler, false);
touchzone.addEventListener("touchstart", touchHandler, false);
}
function touchHandler(event) {
// Get a reference to our coordinates div
var can = document.getElementById("myCanvas");
// Write the coordinates of the touch to the div
var pageX = event.touches ? event.touches[0].pageX : event.pageX;
if (pageX < x * 50) {
ballx += 1;
} else if (pageX > x * 50) {
ballx -= 1;
}
console.log(x, ballx);
draw();
}
initia();
</script>
</body>
</html>