计算具有2种颜色和百分比/位置的颜色十六进制 [英] Calculate color HEX having 2 colors and percent/position

查看:190
本文介绍了计算具有2种颜色和百分比/位置的颜色十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在渐变的中间计算颜色?

Is it possible to calculate a color in a middle of a gradient?

var color1 = 'FF0000';
var color2 = '00FF00';

// 50% between the two colors, should return '808000'
var middle = gradient(color1, color2, 0.5); 

我只有两个十六进制字符串,我想要一个作为回报.

I only have two hex strings, and I want one in return.

推荐答案

这应该有效:

基本上,这涉及到将它们转换为十进制,找到一半,然后将结果转换回十六进制,然后将它们连接起来.

It basically involves converting them to decimal, finding the halves, converting the results back to hex and then concatenating them.

var color1 = 'FF0000';
var color2 = '00FF00';
var ratio = 0.5;
var hex = function(x) {
    x = x.toString(16);
    return (x.length == 1) ? '0' + x : x;
};

var r = Math.ceil(parseInt(color1.substring(0,2), 16) * ratio + parseInt(color2.substring(0,2), 16) * (1-ratio));
var g = Math.ceil(parseInt(color1.substring(2,4), 16) * ratio + parseInt(color2.substring(2,4), 16) * (1-ratio));
var b = Math.ceil(parseInt(color1.substring(4,6), 16) * ratio + parseInt(color2.substring(4,6), 16) * (1-ratio));

var middle = hex(r) + hex(g) + hex(b);

这篇关于计算具有2种颜色和百分比/位置的颜色十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆