HOW TO MAKE AN OBJECT MOVE USING HTML AND JAVASCRIPT
Code: _______________________________________________________________ <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Moving an Object</title> </head> <body> <script> var canvas = document.createElement("canvas"); b = canvas.getContext("2d"); canvas.width = 400; canvas.height = 400; document.body.appendChild(canvas); b.fillStyle = "black"; b.fillRect(0, 0, canvas.width, canvas.height); var posX = 200; posY = 200; dx = 0; dy = 0; setInterval(function () { b.fillStyle = "black"; b.fillRect(0, 0, canvas.width, canvas.height); posX += dx; posY += dy; if (posX > 390) { dx = 0; posX = 390; } if (posX < 0) { dx = 0; posX = 0; } if (posY > 390) { dy = 0; posY = 390; } if (posY < 0) { dy = 0; posY = 0; } b.fillStyle = "white"; b.fillRect(posX, posY, 10, 10); }, 20) window.addEventListener("keydown", press001, true); function press001(event) { switch (event.keyCode) { case 37: dx = -1; dy = 0; break; case 38: dx = 0; dy = -1; break; case 39: dx = 1; dy = 0; break; case 40: dx = 0; dy = 1; break; case 32: dx = 0; dy = 0; break; } } </script> </body> </html> Here is a video of the above code. |
OTHER RELATED PAGES: Learn how to make a quiz Learn how to add an image from your pc to your website Learn how to create a link for your website Learn how to make a scrolling text using html and css Learn how to create an input box using html and javascript Learn how to create a crossword puzzle using html, javascript and css |