I don’t plan to teach canvas, I just took a look at it because I thought it was fun.
It means it's a little rough, so don't criticize me. .
EffectThe frame rate is slightly lower, but the actual performance is of course much smoother.
Implement HTML
<!DOCTYPE html><head> <meta name=viewport content=width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0> <style> * { margin: 0;padding: 0;} body {background-color: lightblue;} #canvas {background-color: black;width: 100vw;} </style></head><body> <canvas id=canvas></canvas> <script>/* See below*/</script></body>JS
window.onload = function () { let // Canvas ctx = document.getElementById('canvas').getContext('2d'), // Canvas size canvas_width = document.getElementById('canvas').width, canvas_height = document .getElementById('canvas').height, // Text color, font, background color of DVD icon text_color = ['green', 'blue', 'purple', 'yellow', 'white', 'yellow', 'white'], text_font = 'italic bold 50px yahei', background_color = ['red', 'orange', 'yellow', ' green', 'blue', 'indigo', 'violet'], // The size of the background rectangle background_width = 110, background_height = 50, // When adding text to the rectangle, the height deviates a bit fix_height = 7, // Speed, each redraw moves 0.5 px speed_x = 0.5, speed_y = 0.5, // Moving direction, initially 'rb' lower right direction = 'rb', // Icon x and y coordinates, initially 0 position_x = 0, position_y = 0, // Number of collisions, used to calculate background and text color count = 0 dvd() function dvd() { // Moving direction switch (direction) { // Lower right case 'rb': position_x += speed_x position_y += speed_y break // Upper right case 'rt': position_x += speed_x position_y -= speed_y break / / Lower left case 'lb': position_x -= speed_x position_y += speed_y break // Upper left case 'lt': position_x -= speed_x position_y -= speed_y break } // Clear the canvas ctx.clearRect(0, 0, canvas_width, canvas_height) // Redraw ctx.fillRect(position_x, position_y, background_width, background_height) // Collision detection // Bottom if (position_y + background_height > = canvas_height) { direction = direction.replace('b', 't') // Collision count count += 1 } // Right if (position_x + background_width >= canvas_width) { direction = direction.replace('r', 'l') count += 1 } // Left if (position_x < 0) { direction = direction.replace(' l', 'r') count += 1 } // upper if (position_y < 0) { direction = direction.replace('t', 'b') count += 1 } // Text ctx.font = text_font ctx.fillStyle = text_color[count % 7] ctx.fillText(DVD, position_x, position_y + background_height - fix_height) // Background color ctx.fillStyle = background_color[count % 7] // Start animation window. requestAnimationFrame(dvd) }}The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.