繁体   English   中英

使用JavaScript在画布上移动对象

[英]Making an object move on canvas in JavaScript

我试图用JavaScript制作一个简单的游戏,其中您使用箭头键在画布上移动对象(圆/球)。 我花了很多时间进行研究和编码,但是到目前为止还没有运气,所以我希望你们能帮助我。 现在,我只是尝试使用箭头键[上,下,左,右]移动对象/球。 任何人都可以弄清楚,为什么这行不通? 提前非常感谢您。

 var canvas = document.getElementById("mycanvas"); var ctx = canvas.getContext("2d"); canvas.width = canvas.height = 500; //the circle function circle() { ctx.beginPath(); ctx.arc(50, 50, 25, 0, Math.PI * 2, true); ctx.fillStyle = "blue"; ctx.fill(); } circle(); //move function for going left window.addEventListener("keydown", function(event) { if (event.keyCode == 37) { circle.x = 1; } }) 

您可以通过以下方式完成这种移动...

 var canvas = document.getElementById("mycanvas"); var ctx = canvas.getContext("2d"); var x = 50, y = 50, radius = 15, speed = 3; function circle() { ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI * 2, true); ctx.fillStyle = "#07C"; ctx.fill(); } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); circle(); requestAnimationFrame(draw); } draw(); window.addEventListener("keydown", function(e) { switch (e.key) { case 'ArrowUp': if (y > radius) y -= speed; break; case 'ArrowDown': if (y < canvas.height - radius) y += speed; break; case 'ArrowLeft': if (x > radius) x -= speed; break; case 'ArrowRight': if (x < canvas.width - radius) x += speed; break; } }); 
 canvas { border: 1px solid black; } 
 <canvas id="mycanvas" width="200" height="200"></canvas> 

道歉,没有给出任何解释

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM