HTML5動(dòng)態(tài)矩形是Web開發(fā)中常見的一個(gè)特效。下面是一個(gè)HTML5動(dòng)態(tài)矩形的代碼示例:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>動(dòng)態(tài)矩形</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>
上面這段代碼可以創(chuàng)建一個(gè)500 * 500大小的矩形,矩形的長度寬度一開始都是0,隨著時(shí)間的推移,它會(huì)不斷增長或縮小。當(dāng)矩形到達(dá)畫布邊緣時(shí),它就會(huì)反向增長或縮小。這種不斷變化和動(dòng)態(tài)的效果讓網(wǎng)站變得更加生動(dòng)、有趣。編寫HTML5動(dòng)態(tài)矩形需要了解JavaScript中的canvas和requestAnimationFrame這兩個(gè)重要的API。