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

如何在JavaScript中动态修改Rive文件内对象的颜色?

在JavaScript中动态修改Rive对象颜色的实现方法

完全可以通过Rive的JavaScript API动态修改文件中对象的颜色,核心是定位到目标形状对象后,修改其填充或描边的颜色属性。以下是具体实现步骤:

前提准备

在Rive编辑器里,要修改的对象必须是可编辑的Shape节点,并且记住它的名称(在编辑器层级面板中查看),方便后续代码定位。

修改现有代码实现变色

结合你提供的代码,在onLoad回调或需要触发变色的时机(比如按钮点击)中,添加颜色修改逻辑:

const r = new rive.Rive({
  src: "email6.riv",
  canvas: document.getElementById("canvas"),
  autoplay: true,
  artboard: "New Artboard",
  stateMachines: "email_hover",

  onLoad: () => {
    r.resizeDrawingSurfaceToCanvas();
    
    // 获取当前加载的Artboard
    const artboard = r.artboard;
    // 替换成你要修改的Shape节点名称
    const targetShape = artboard.find("目标形状名称");
    
    if (targetShape) {
      // 修改填充颜色:参数为RGBA值,范围0-255
      targetShape.fills.forEach(fill => {
        fill.color = new rive.Color(255, 0, 0, 255); // 设置为红色
      });
      
      // 若需要修改描边颜色,取消下面注释
      // targetShape.strokes.forEach(stroke => {
      //   stroke.color = new rive.Color(0, 255, 0, 255); // 设置为绿色
      // });
      
      // 标记画布需要重绘,让颜色修改生效
      r.redraw();
    }
  },
});

找不到形状名称?遍历节点查找

如果不清楚目标形状的准确名称,可以通过遍历Artboard的节点树来定位:

// 递归遍历节点,查找指定名称的Shape
function findTargetShape(artboard, targetName) {
  function traverse(node) {
    if (node.name === targetName && node instanceof rive.Shape) {
      return node;
    }
    if (node.children) {
      for (const child of node.children) {
        const result = traverse(child);
        if (result) return result;
      }
    }
    return null;
  }
  return traverse(artboard);
}

// 在onLoad中使用:
// const targetShape = findTargetShape(artboard, "目标形状名称");

动态触发颜色修改

如果需要在用户交互(比如按钮点击)时变色,可以绑定事件:

<!-- 在body中添加按钮 -->
<button id="changeColorBtn">切换颜色</button>
// 在onLoad之后或全局作用域中绑定事件
document.getElementById("changeColorBtn").addEventListener("click", () => {
  const artboard = r.artboard;
  const targetShape = artboard.find("目标形状名称");
  if (targetShape) {
    // 随机切换颜色示例
    const randomColor = new rive.Color(
      Math.floor(Math.random()*256),
      Math.floor(Math.random()*256),
      Math.floor(Math.random()*256),
      255
    );
    targetShape.fills.forEach(fill => fill.color = randomColor);
    r.redraw();
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 17:22:31