HTML5動態矩形是Web開發中常見的一個特效。下面是一個HTML5動態矩形的代碼示例:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>動態矩形</title> <style> canvas{border:1px solid #d3d3d3;} </style> </head> <body> <canvas id="canvas" width="500" height="500"></canvas> <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var x = 0; var y = 0; var width = 0; var height = 0; var growRate = 10; var shrinkRate = -10; var growing = true; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); if (growing) { width += growRate; height += growRate; x -= growRate / 2; y -= growRate / 2; } else { width += shrinkRate; height += shrinkRate; x -= shrinkRate / 2; y -= shrinkRate / 2; } if (width >canvas.width || height >canvas.height) { growing = false; } else if (width< 0 || height< 0) { growing = true; } ctx.fillRect(x, y, width, height); window.requestAnimationFrame(draw); } draw(); </script> </body> </html>
上面這段代碼可以創建一個500 * 500大小的矩形,矩形的長度寬度一開始都是0,隨著時間的推移,它會不斷增長或縮小。當矩形到達畫布邊緣時,它就會反向增長或縮小。這種不斷變化和動態的效果讓網站變得更加生動、有趣。編寫HTML5動態矩形需要了解JavaScript中的canvas和requestAnimationFrame這兩個重要的API。
上一篇html5動態背景代碼