使用HTML5绘制一个发光的灯泡

在HTML5中,你可以使用<canvas>元素与JavaScript来绘制一个发光的灯泡。下面是一个简单的示例,展示了如何创建一个基础的发光灯泡效果:

  1. HTML结构
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发光的灯泡</title>
    <style>
        body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
        canvas { border: 1px solid black; }
    </style>
</head>
<body>
    <canvas id="lightBulbCanvas" width="400" height="400"></canvas>
    <script src="script.js"></script>
</body>
</html>
  1. JavaScript代码 (script.js 文件):
const canvas = document.getElementById('lightBulbCanvas');
const ctx = canvas.getContext('2d');

// 绘制灯泡的函数
function drawLightBulb() {
    // 灯泡的外部轮廓
    ctx.beginPath();
    ctx.arc(200, 200, 100, 0, Math.PI * 2, false); // 外圆
    ctx.fillStyle = 'yellow';
    ctx.fill();
    ctx.lineWidth = 5;
    ctx.strokeStyle = 'orange';
    ctx.stroke();

    // 灯泡的内部轮廓(发光部分)
    ctx.beginPath();
    ctx.arc(200, 200, 70, 0, Math.PI * 2, false); // 内圆
    ctx.fillStyle = 'white';
    ctx.fill();
    ctx.strokeStyle = 'yellow';
    ctx.stroke();

    // 灯泡的底部
    ctx.beginPath();
    ctx.rect(150, 200, 100, 30); // 矩形底部
    ctx.fillStyle = 'orange';
    ctx.fill();
    ctx.stroke();

    // 灯泡的发光效果(使用径向渐变)
    const gradient = ctx.createRadialGradient(200, 200, 70, 200, 200, 100);
    gradient.addColorStop(0, 'rgba(255, 255, 255, 1)'); // 白色中心
    gradient.addColorStop(1, 'rgba(255, 255, 0, 0)'); // 黄色边缘,透明度为0
    ctx.beginPath();
    ctx.arc(200, 200, 100, 0, Math.PI * 2, false); // 外圆,用于发光效果
    ctx.fillStyle = gradient;
    ctx.fill();
}

// 绘制灯泡
drawLightBulb();

这段代码创建了一个简单的发光灯泡效果。它使用HTML5的<canvas>元素和JavaScript来绘制灯泡的轮廓,并通过径向渐变来模拟发光效果。你可以根据需要调整颜色、大小和其他属性来定制灯泡的外观。

posted @   王铁柱6  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示