#HTML 的 <canvas> 标签
请查看 HTML 元素帮助手册 了解更多 HTML 元素。
<canvas> 元素可被用来通过 JavaScript(Canvas API 或 WebGL API)绘制图形及图形动画。
#属性
请查看 HTML 元素的全局属性 了解 HTML 元素的全局属性。
height: 该元素占用空间的高度,以 CSS 像素(px)表示,默认为 150。moz-opaque(废弃): 通过设置这个属性,来控制 canvas 元素是否半透明。如果你不想 canvas 元素被设置为半透明,使用这个元素将可以优化浏览器绘图性能。width: 该元素占用空间的宽度,以 CSS 像素(px)表示,默认为 300。
#示例
<canvas>1<canvas id="myCanvas"> 2</canvas> 3 4<script> 5 // 2. 获取 Canvas 上下文 6 const canvas = document.getElementById("myCanvas"); 7 const ctx = canvas.getContext("2d"); 8 9 // 3. 设置画布尺寸为窗口大小 10 canvas.width = window.innerWidth; 11 canvas.height = window.innerHeight; 12 13 // 4. 定义小球对象 14 const ball = { 15 x: canvas.width / 2, 16 y: canvas.height / 2, 17 radius: 20, 18 dx: 4, // x轴速度 19 dy: 4, // y轴速度 20 color: `hsl(${Math.random() * 360}, 70%, 50%)` 21 }; 22 23 // 5. 绘制小球的函数 24 function drawBall() { 25 ctx.beginPath(); 26 ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2); 27 ctx.fillStyle = ball.color; 28 ctx.fill(); 29 ctx.closePath(); 30 } 31 32 // 6. 动画循环 33 function animate() { 34 // 清空画布(半透明效果会产生拖尾) 35 ctx.fillStyle = "rgba(255, 255, 255, 0.1)"; 36 ctx.fillRect(0, 0, canvas.width, canvas.height); 37 38 drawBall(); 39 40 // 碰撞检测(碰到边缘反弹) 41 if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0) { 42 ball.dx = -ball.dx; 43 ball.color = `hsl(${Math.random() * 360}, 70%, 50%)`; // 随机变色 44 } 45 if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) { 46 ball.dy = -ball.dy; 47 ball.color = `hsl(${Math.random() * 360}, 70%, 50%)`; 48 } 49 50 // 更新位置 51 ball.x += ball.dx; 52 ball.y += ball.dy; 53 54 requestAnimationFrame(animate); 55 } 56 57 // 7. 启动动画 58 animate(); 59</script> 60
#推荐阅读
《HTML 的 <canvas> 标签》 是转载文章,点击查看原文。