tinycolor().brighten() 异常求助:复用实例后颜色亮度不符合预期如何解决?
问题:tinycolor2复用实例后颜色生成异常
我使用tinycolor2工具,希望基于brandColor_Base生成更亮的颜色。最初的代码每次调用tinycolor(brandColor_Base)执行brighten方法,能正常工作:
import tinycolor from "tinycolor2" const brandColor_Base="#338EF5"; export var colors={ brandColor_1:tinycolor(brandColor_Base).brighten(70).toString(), brandColor_2:tinycolor(brandColor_Base).brighten(55).toString(), brandColor_3:tinycolor(brandColor_Base).brighten(40).toString(), brandColor_4:tinycolor(brandColor_Base).brighten(25).toString(), brandColor_5:tinycolor(brandColor_Base).brighten(10).toString(), brandColor_6:tinycolor(brandColor_Base), }
但为了避免重复编写tinycolor(brandColor_Base),我修改了代码,直接把brandColor_Base赋值为tinycolor实例:
import tinycolor from "tinycolor2" const brandColor_Base=tinycolor("#338EF5"); export var colors={ brandColor_1:brandColor_Base.brighten(70).toString(), brandColor_2:brandColor_Base.brighten(55).toString(), brandColor_3:brandColor_Base.brighten(40).toString(), brandColor_4:brandColor_Base.brighten(25).toString(), brandColor_5:brandColor_Base.brighten(10).toString(), }
修改后出现异常:brandColor_5比brandColor_4亮,brandColor_4比brandColor_3亮,所有生成的颜色都没有比brandColor_Base更亮;删除前面的代码行时,brandColor_5还会变暗。请问该如何解决?
解决方案
问题原因
tinycolor2的brighten方法是直接修改原实例的,不是返回全新实例。复用同一个brandColor_Base实例时,每次调用brighten都是在之前修改后的颜色基础上继续调整,导致后续颜色计算完全偏离预期。
解决方法
方法1:使用clone()复制实例
每次调整颜色前,通过clone()复制原始基础色实例,确保每次调整的都是原始颜色的副本,不会修改原实例:
import tinycolor from "tinycolor2" const brandColor_Base = tinycolor("#338EF5"); export const colors = { brandColor_1: brandColor_Base.clone().brighten(70).toString(), brandColor_2: brandColor_Base.clone().brighten(55).toString(), brandColor_3: brandColor_Base.clone().brighten(40).toString(), brandColor_4: brandColor_Base.clone().brighten(25).toString(), brandColor_5: brandColor_Base.clone().brighten(10).toString(), }
方法2:保留基础色为字符串(原始写法)
保持brandColor_Base为字符串,每次调用tinycolor()创建新实例,确保每个颜色都基于原始基础色计算:
import tinycolor from "tinycolor2" const brandColor_Base = "#338EF5"; export const colors = { brandColor_1: tinycolor(brandColor_Base).brighten(70).toString(), brandColor_2: tinycolor(brandColor_Base).brighten(55).toString(), brandColor_3: tinycolor(brandColor_Base).brighten(40).toString(), brandColor_4: tinycolor(brandColor_Base).brighten(25).toString(), brandColor_5: tinycolor(brandColor_Base).brighten(10).toString(), brandColor_6: tinycolor(brandColor_Base), }
内容的提问来源于stack exchange,提问作者Aya Abdessalem
相关产品推荐
相关产品推荐

