我正在尝试制作HTML5 Canvas / JavaScript游戏。我看了一些教程,并且我理解了每个人的意思,但是我没有为触摸设备提供正确的控制。
我希望得到我的'飞艇',我的手指触摸屏幕。它不仅适用于鼠标定位的位置。
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<script type="text/javascript">
window.onload = function() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var canvasWidth = canvas.offsetWidth;
var canvasHeight = canvas.offsetHeight;
var bg1 = new Image();
var bg2 = new Image();
bg1.src = "img/spritesheet.png";
bg2.src = "img/spritesheet.png";
var increment = -5;
var sYbg1 = 0;
var sYbg2 = 960;
var ship = new Image();
ship.src = "img/spritesheet.png";
var mouseX;
var mouseY;
canvas.onmousemove = function() {
mouseX = window.event.clientX - canvas.offsetLeft; // mousePositionX
inside the <canvas> element
mouseY = window.event.clientY - canvas.offsetTop; // mousePositionY
inside the <canvas> element
};
var animate = function() {
context.clearRect(0,0,canvasWidth,canvasHeight);
context.drawImage(bg1,0,sYbg1,canvasWidth,canvasHeight,0,0,canvasWidth,canvasHeight);
context.drawImage(bg2,0,sYbg2,canvasWidth,canvasHeight,0,0,canvasWidth,canvasHeight);
sYbg1 += increment;
sYbg2 += increment;
if(sYbg2 <= 0) {
sYbg1 = 0;
sYbg2 = 960;
}
context.drawImage(ship,320,0,65,105,(mouseX-32),(mouseY-52),65,105);
setTimeout(animate,25);
};
animate();
}
</script>
</head>
<body>
<canvas id="canvas" width="320" height="480"></canvas>
</body>
</html>
(!我的代码只在CHROME工作!) - &gt;但这并不重要,我知道window.event并且它在FF中不起作用。
我希望有人可以向我解释我需要做什么。我试图解决我的问题,一起使用onmousemove和onmousedown,但这对我也没有用。非常感谢您的帮助!
答案 0 :(得分:0)
如果你还没有到那里,我会提供一些提示,以及未来的研究人员。你有一个鼠标事件处理程序(mousemove)。我没有看到触摸事件处理程序。有些选项取决于您的浏览器,我不清楚您要使用哪个... 但是,您可以开始将https://developers.google.com/或MDN https://developer.mozilla.org/en-US/视为良好的起点。