如何在JavaScript熔岩灯特效中使用SCSS变量替换颜色值
解决方案
1. 获取CSS变量的实际颜色值
通过getComputedStyle获取:root上定义的CSS变量值,确保能拿到最终生效的颜色:
// 获取根元素的计算样式 const rootStyles = getComputedStyle(document.documentElement); // 提取CSS变量并去除多余空格 const cssWhite = rootStyles.getPropertyValue('--white').trim(); const cssBlack = rootStyles.getPropertyValue('--black').trim();
2. 转换颜色格式适配PIXI
PIXI使用0x开头的十六进制格式,需要把CSS的#RRGGBB格式转换为对应格式:
// 转换函数:将#开头的十六进制颜色转为0x开头 function hexToPixiColor(hex) { return `0x${hex.replace('#', '')}`; } // 得到适配PIXI的颜色值 const pixiWhite = hexToPixiColor(cssWhite); const pixiBlack = hexToPixiColor(cssBlack);
3. 替换颜色数组中的硬编码值
将原数组里的硬编码颜色替换为转换后的CSS变量对应值:
// Make a nice color pallete for our random orbs const colors = [pixiWhite, pixiBlack, "0x7209b7", "0xf72585"]; const blurFilter2 = new PIXI.BlurFilter();
完整整合代码
CSS部分
:root { --black: #000000; --white: #ffffff; }
JavaScript部分
// 获取并转换CSS变量为PIXI可用格式 const rootStyles = getComputedStyle(document.documentElement); const cssWhite = rootStyles.getPropertyValue('--white').trim(); const cssBlack = rootStyles.getPropertyValue('--black').trim(); function hexToPixiColor(hex) { return `0x${hex.replace('#', '')}`; } const pixiWhite = hexToPixiColor(cssWhite); const pixiBlack = hexToPixiColor(cssBlack); // 使用CSS变量对应的颜色定义数组 const colors = [pixiWhite, pixiBlack, "0x7209b7", "0xf72585"]; const blurFilter2 = new PIXI.BlurFilter();
内容的提问来源于stack exchange,提问作者Rob
相关产品推荐
相关产品推荐

