You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Javascript/HTML修改平面图黄色区域颜色适配智能灯泡RGB值

最简实现方案

嘿,这个需求其实不难搞定,我给你两种最简洁的实现思路,你可以根据自己的实际情况选择:

方案一:用SVG重构黄色区域(推荐)

如果你的房屋平面图可以转换成SVG格式,把需要变色的黄色区域单独做成一个可识别的SVG元素(比如<path>或<rect>),这是最灵活且性能友好的方式:

代码示例

<!-- 假设这是你的SVG平面图,黄色区域已经定义了ID -->
<svg width="800" height="600" viewBox="0 0 800 600">
  <!-- 其他固定的平面图元素 -->
  <path id="color-room" d="M150,120 L280,120 L280,240 L150,240 Z" fill="#ffff00" />
</svg>

<script>
// 获取需要变色的SVG元素
const colorableArea = document.getElementById('color-room');

// 模拟获取灯泡RGB值的函数,实际替换成你的内部API调用
async function getBulbRGB() {
  // 真实场景下替换成你的请求逻辑:
  // const res = await fetch('/api/smart-bulb/rgb');
  // const { r, g, b } = await res.json();
  // return `rgb(${r}, ${g}, ${b})`;

  // 测试用:返回随机RGB值
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r}, ${g}, ${b})`;
}

// 更新区域颜色的函数
async function updateColor() {
  try {
    const rgbColor = await getBulbRGB();
    colorableArea.setAttribute('fill', rgbColor);
  } catch (err) {
    console.error('更新灯泡颜色失败:', err);
  }
}

// 初始化加载一次,然后每10秒轮询
updateColor();
// 用递归setTimeout替代setInterval,避免请求堆积
function startPolling() {
  setTimeout(async () => {
    await updateColor();
    startPolling();
  }, 10000);
}
startPolling();
</script>

方案二:用Div覆盖变色区域(无需修改原图)

如果不想改动现有的平面图图片,可以用一个绝对定位的<div>精准覆盖在黄色区域上方,动态修改它的背景色:

代码示例

<!-- 平面图容器,用相对定位让覆盖层可以基于它定位 -->
<div style="position: relative; width: 800px; height: auto;">
  <img src="your-floor-plan.png" alt="房屋平面图" style="width: 100%;" />
  <!-- 这个div的top/left/width/height要和黄色区域完全匹配,自己调整数值 -->
  <div id="color-overlay" style="position: absolute; top: 120px; left: 150px; width: 130px; height: 120px; background-color: #ffff00;"></div>
</div>

<script>
const colorOverlay = document.getElementById('color-overlay');

async function getBulbRGB() {
  // 同样替换成你的API调用逻辑
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r}, ${g}, ${b})`;
}

async function updateOverlayColor() {
  try {
    const rgbColor = await getBulbRGB();
    colorOverlay.style.backgroundColor = rgbColor;
  } catch (err) {
    console.error('获取灯泡颜色出错:', err);
  }
}

// 初始化+轮询
updateOverlayColor();
function pollColor() {
  setTimeout(async () => {
    await updateOverlayColor();
    pollColor();
  }, 10000);
}
pollColor();
</script>

额外提示

  • 优先选SVG方案,因为它是矢量图,缩放不会失真,而且颜色修改是直接操作元素属性,性能更好。
  • 用递归setTimeout替代setInterval的好处是:如果某次API请求超时或失败,不会导致后续请求堆积,轮询间隔会从请求完成后重新计算10秒。
  • 如果必须直接修改原图的像素(不推荐),可以用Canvas绘制图片后遍历像素替换黄色,但这个逻辑相对复杂,适合无法用前两种方案的场景。

内容的提问来源于stack exchange,提问作者av4625

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:45:34