"Sure, here's an example of HTML code that includes a canvas with a ball that can be moved using arrow keys and wraps around the canvas when it reaches the edges:
<html> <head> <title>Canvas Ball Movement</title> <style> canvas { border: 1px solid black; } </style> </head> <body> <canvas id="myCanvas" width="500" height="500"></canvas> <script> // Get the canvas and context var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); // Set the initial position of the ball var ballX = canvas.width / 2; var ballY = canvas.height / 2; // Set the ball's radius and speed var ballRadius = 10; var ballSpeed = 5; // Handle key presses to move the ball document.addEventListener("keydown", function(event) { if (event.keyCode === 37) { // Move left ballX -= ballSpeed; } else if (event.keyCode === 38) { // Move up ballY -= ballSpeed; } else if (event.keyCode === 39) { // Move right ballX += ballSpeed; } else if (event.keyCode === 40) { // Move down ballY += ballSpeed; } // Wrap the ball around the canvas edges if (ballX < 0) { ballX = canvas.width; } else if (ballX > canvas.width) { ballX = 0; } if (ballY < 0) { ballY = canvas.height; } else if (ballY > canvas.height) { ballY = 0; } // Redraw the ball drawBall(); }); // Draw the ball on the canvas function drawBall() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.arc(ballX, ballY, ballRadius, 0, Math.PI*2); ctx.fillStyle = "red"; ctx.fill(); ctx.closePath(); } // Draw the initial ball drawBall(); </script> </body> </html>
This code creates a canvas with a width and height of 500 pixels, and sets the initial position of the ball to the center of the canvas. The ball's radius is set to 10 pixels and its speed is set to 5 pixels per key press.
The code listens for key presses using document.addEventListener("keydown") and moves the ball accordingly. If the ball goes off the edges of the canvas, the code wraps it around to the other side.
The drawBall() function is called to redraw the ball after each key press, clearing the canvas first with ctx.clearRect() and then drawing the ball with ctx.beginPath() and ctx.arc(). The ball is filled with red color using ctx.fillStyle and ctx.fill(), and the path is closed using ctx.closePath(). Finally, the initial ball is drawn by calling drawBall() once at the end of the script." -ChatGPT
No comments:
Post a Comment