图示:
核心代码:
//将0x格式的颜色转换为Hex格式,并计算插值返回rgb颜色
Vue.prototype.$convertToHex = function (colorCode1, colorCode2, amount) {
// 确保输入是字符串,并检查是否以'0x'开头
let newCode1 = ''
let newCode2 = ''
if (typeof colorCode1 === 'string' && colorCode1.startsWith('0x')) {
// 移除'0x'前缀并返回新的十六进制字符串 // 从索引2开始取子串(跳过'0x')
newCode1 = '#' + colorCode1.substring(2)
}
if (typeof colorCode2 === 'string' && colorCode2.startsWith('0x')) {
// 移除'0x'前缀并返回新的十六进制字符串 // 从索引2开始取子串(跳过'0x')
newCode2 = '#' + colorCode2.substring(2)
}
// 将颜色字符串转换为RGB对象
let rgb1 = {
r: parseInt(newCode1.substring(1, 3), 16),
g: parseInt(newCode1.substring(3, 5), 16),
b: parseInt(newCode1.substring(5, 7), 16)
};
let rgb2 = {
r: parseInt(newCode2.substring(1, 3), 16),
g: parseInt(newCode2.substring(3, 5), 16),
b: parseInt(newCode2.substring(5, 7), 16)
};
// 插值计算
let r = Math.round(rgb1.r + (rgb2.r - rgb1.r) * amount);
let g = Math.round(rgb1.g + (rgb2.g - rgb1.g) * amount);
let b = Math.round(rgb1.b + (rgb2.b - rgb1.b) * amount);
let colorRGB = `rgb(${r},${g},${b})`
return colorRGB
}
使用方法:
let colorCode1 = "0x00FF2F"
let colorCode2 = "0xFEA90B"
let amount = 0.6 // 插值
console.log('获取到的rgb格式颜色值', this.$convertToHex(colorCode1,colorCode2,amount))
案例(根据温度值数字算渐变值):
//0x格式颜色值
let gradientObj={
16: "0x00FF2F",
32: "0xFEA90B",
36: "0xFF3300",
-40: "0x061BFC",
}
//判断数字是否小于等于对象的key值,相同就拿出对应的value值,并返回当前的rgb值
changeBgColor(num) {
let colorCode1 = ''
let colorCode2 = ''
let amount = 1
let keys = Object.keys(this.gradientData)
keys.sort((a, b) => {
return a - b;
});
if (num <= parseInt(keys[0])) {
colorCode1 = this.gradientData[keys[0]]
colorCode2 = this.gradientData[keys[0]]
} else if (num >= parseInt(keys[keys.length - 1])) {
colorCode1 = this.gradientData[keys[keys.length - 1]]
colorCode2 = this.gradientData[keys[keys.length - 1]]
} else {
for (let i = 0; i < keys.length - 1; i++) {
if (num >= keys[i] && num <= keys[i + 1]) {
colorCode1 = this.gradientData[keys[i]]
colorCode2 = this.gradientData[keys[i + 1]]
amount = (num * 1.0 - keys[i]) / (keys[i + 1] - keys[i]); // 根据温度值计算插值比例
break;
}
}
}
return this.$convertToHex(colorCode1, colorCode2, amount)
},
案例使用:
this.changeBgColor(30.25) //输入值为:rgb(226, 178, 15)