一款简单的拾色器:ColorTool拾色器

介绍

这个是为我自己写得,因为我觉得如果需要获取网页上的某个颜色总是需要打开“开发者中心”的话太麻烦了;简单易用、易懂,仅使用JavaScript语言编写。

它长这样:

使用

仅调用:一行代码即可搞定

ColorPicker("#000000");

调用后执行其他程序

ColorPicker("#000000").then(function(){});

取得颜色rgb值

ColorPicker("#008CD6").then(function(ColorData){console.log(ColorData)});

随时直接设置、更改颜色:一行代码即可搞定

ColorPicker.setColor("#000000");

 以上代码均与它无关

关键代码

if ('EyeDropper' in window) { // 判断是否支持这个api
	let eyeDropper = new EyeDropper(); // 创建对象
	ColorPicker.prototype.Ele.getColor.addEventListener('click', async () => { 
		try {
		     const ColorResult = await eyeDropper.open();// 取得吸取结果
		     ColorPicker.setColor(ColorResult.sRGBHex);// 取得颜色并设置颜色
		} catch (e) {
		     console.warn('你取消了取色操作')
		}
	});
}

源码在这里

目录结构:

 popup.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>ColorTool拾色器</title>
		<link rel="stylesheet" href="./icomoon/style.css">
		<link rel="stylesheet" href="./css/index.css">
		<script src="./javascript/ColorTool.js"></script>
	</head>
	<body>
		<div class="main">
			<div class="sample"></div>
			<div class="ColorToolContainer">
				<div class="PanelContainer">
					<canvas id="panelCanvas" width="216" height="124">
						Your browser does not support canvas
					</canvas>
					<div class="DotOne"></div>
				</div>
				<div class="BarContainer">
					<div class="Discoloration">
						<div class="DotTwo"></div>
					</div>
				</div>
				<div class="other">
					<div class="InputBoxContainer">
						<div class="InputBoxOne">
							<input value="#ff0000" spellcheck="false" maxlength="7">
							<span>HEX(十六进制)</span>
						</div>
						<div class="InputBoxTwo">
							<div>
								<input class="colorpicker-hexInput" value="255" maxlength="3" spellcheck="false">
								<span>r</span>
							</div>
							<div>
								<input class="colorpicker-hexInput" value="0" maxlength="3" spellcheck="false">
								<span>g</span>
							</div>
							<div>
								<input class="colorpicker-hexInput" value="0" maxlength="3" spellcheck="false">
								<span>b</span>
							</div>
						</div>
						<div class="InputBoxThree">
							<div>
								<input class="colorpicker-hslInput" value="255" maxlength="4" spellcheck="false">
								<span>h</span>
							</div>
							<div>
								<input class="colorpicker-hslInput" value="0" maxlength="4" spellcheck="false">
								<span>s</span>
							</div>
							<div>
								<input class="colorpicker-hslInput" value="0" maxlength="4" spellcheck="false">
								<span>l</span>
							</div>
						</div>
					</div>
					<div class="control">
						<button>重置</button>
						<div class="LeftAndRight">
							<span class="left">
								<i class="icon-custom-10"></i>
							</span>
							<span class="right">
								<i class="icon-custom-9"></i>
							</span>
						</div>
					</div>
				</div>
			</div>
			
			<button class="getColor">吸取颜色</button>
		</div>
		<script src="./javascript/index.js"></script>
	</body>
</html>

index.css

* {
	margin: 0px;
	padding: 0px;
	box-sizing: border-box;
}

body {
	width: 100vw;
	min-width: 230px;
	height: 100vh;
	min-height: 295px;
	background-color: #f3f3f3;
}

body,
.BarContainer,
.other,
.InputBoxTwo,
.InputBoxThree {
	display: flex;
	align-items: center;
	justify-content: center;
}

.main {
	width: 230px;
	padding: 7px;
	border-radius: 3px;
	background-color: #FFFFFF;
}

.sample {
	width: 100%;
	height: 30px;
	cursor: move;
	border-radius: 3px;
	background-color: #ff0000;
}

.ColorToolContainer {
	width: 100%;
	margin-top: 10px;
	position: relative;
}

.PanelContainer {
	width: 100%;
	height: 124px;
	overflow: hidden;
	position: relative;
}

#panelCanvas{
	max-width: 100%;
	max-height: 100%;
}

.BarContainer {
	width: 100%;
	height: 15px;
	margin-top: 7px;
}

.Discoloration {
	width: 100%;
	height: 15px;
	position: relative;
	overflow: hidden;
	background-image: linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
}

.other {
	width: 100%;
	margin-top: 7px;
}

input {
	outline: none;
}

.InputBoxOne,
.InputBoxOne>input {
	width: 161px;
}

.InputBoxOne>input {
	font-size: 12px;
	color: rgb(51, 51, 51);
	width: 100%;
	border-radius: 3px;
	border: none;
	box-shadow: rgb(218, 218, 218) 0px 0px 0px 1px inset;
	height: 21px;
	text-align: center;
	box-sizing: border-box;
}

.InputBoxTwo,
.InputBoxThree {
	width: 161px;
	height: 46px;
	display: none;
}

.InputBoxTwo>div,
.InputBoxThree>div {
	width: 49px;
}

.InputBoxTwo>div+div,
.InputBoxThree>div+div {
	margin-left: 7px;
}

.InputBoxTwo>div>input,
.InputBoxThree>div>input {
	font-size: 12px;
	color: rgb(51, 51, 51);
	width: 100%;
	border-radius: 2px;
	border: none;
	box-shadow: rgb(218, 218, 218) 0px 0px 0px 1px inset;
	height: 21px;
	text-align: center;
}

.InputBoxOne>span,
.InputBoxTwo>div>span,
.InputBoxThree>div>span {
	text-transform: uppercase;
	font-size: 12px;
	line-height: 16px;
	color: rgb(150, 150, 150);
	text-align: center;
	display: block;
	height: 16px;
	margin-top: 7px;
}

.control>button {
	width: 49px;
	height: 21px;
	margin-left: 6px;
	color: #606266;
	cursor: pointer;
	box-sizing: border-box;
	border: 1px solid #cccccc;
	background-color: #ffffff;
	border-radius: 2px;
}

.LeftAndRight {
	width: 49px;
	height: 16px;
	margin-left: 6px;
	margin-top: 7px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.left,
.right {
	width: 50%;
	height: 16px;
	display: inline-block;
	font-size: 12px;
	line-height: 16px;
	font-weight: bold;
	text-align: center;
	color: rgb(150, 150, 150);
}

.DotOne,
.DotTwo {
	width: 15px;
	height: 15px;
	left: -6px;
	border-radius: 50%;
	position: absolute;
	box-shadow: 0px 0px 3px rgb(0 0 0 / 80%);
}

.DotOne {
	box-sizing: border-box;
	border: 3px solid #f3f3f3;
	top: -6px;
	background-color: transparent;
}

.DotTwo {
	background-color: transparent;
    box-sizing: border-box;
    border: 3px solid #ffffff;
}

.getColor{
	width: 100%;
	height: 21px;
	margin-top: 5px;
	color: #606266;
	cursor: pointer;
	box-sizing: border-box;
	border: 1px solid #cccccc;
	background-color: #ffffff;
	border-radius: 2px;
}

index.js

(function(){
	const colorData = localStorage.getItem("ColorToolStorage") || "#008CD6";
	ColorTool(colorData).then(function(ColorData){
		// console.log(ColorData) // 颜色数据
	});
})(window);

ColorTool.js

(function(event) {
	event = event || document;
	let rgba = {
			r: 0,
			g: 0,
			b: 0,
			a: 1
		},
		hsb = {
			h: 0,
			s: 100,
			b: 100
		};

	let Initial = null,
		setTime = null,
		throttle = null;

	function ColorTool(str) {
		ColorTool.prototype.Ele = {
			sample: document.querySelector('.sample'),
			ColorToolContainer: document.querySelector('.ColorToolContainer'),
			PanelContainer: document.querySelector('.PanelContainer'),
			panelCanvas: document.querySelector('#panelCanvas'),
			DotOne: document.querySelector('.DotOne'),
			Discoloration: document.querySelector('.Discoloration'),
			DotTwo: document.querySelector('.DotTwo'),
			input: document.querySelectorAll('input'),
			ControlButton: document.querySelector('.control>button'),
			LeftAndRightlSpan: document.querySelectorAll('.LeftAndRight>span'),
			InputBoxOne: document.querySelector('.InputBoxOne'),
			InputBoxTwo: document.querySelector('.InputBoxTwo'),
			InputBoxThree: document.querySelector('.InputBoxThree'),
			getColor: document.querySelector(".getColor"),
			constant:0
		};
		Initial = str;
		return new ColorTool.prototype.init(str);
	}
	ColorTool.prototype.init = function(str) {
		ColorTool.prototype.initANDsetColor(str);
		ColorTool.prototype.getColorFun();
		return this;
	}

	ColorTool.prototype.init.prototype = ColorTool.prototype;

	ColorTool.prototype.then = function(parameter) {
		ColorTool.prototype.then.prototype.thenFun = parameter;
	}

	ColorTool.setColor = function(str) {
		if (ColorTool.prototype.initANDsetColor) {
			ColorTool.prototype.initANDsetColor(str);
		} else {
			throw new Error('未调用ColorTool函数');
		}
	}
	
	ColorTool.prototype.getColorFun = function() {
		if ('EyeDropper' in window) { // 判断是否支持这个api
		  let eyeDropper = new EyeDropper(); // 创建对象
		  ColorTool.prototype.Ele.getColor.addEventListener('click', async () => { 
		    try {
		      const ColorResult = await eyeDropper.open();// 取得吸取结果
		      ColorTool.setColor(ColorResult.sRGBHex);// 取得颜色并设置颜色
		    } catch (e) {
		      console.warn('你取消了取色操作')
		    }
		  });
		}
	}

	ColorTool.prototype.initANDsetColor = function(str) {
		if (str.match(/rgb\(|\Rgb\(/g) && str.match(/\)|\);/g) && str.match(/,/g)) {
			if (str.match(/,/g).length === 2) {
				str = str.replace(/rgb\(|\Rgb\(/g, '').replace(/\)|\);/g, '');
				let strArr = str.split(',');
				ColorTool.prototype.Ele.input[1].value = parseInt(strArr[0]);
				ColorTool.prototype.Ele.input[2].value = parseInt(strArr[1]);
				ColorTool.prototype.Ele.input[3].value = parseInt(strArr[2]);
				ColorTool.prototype.RgbInput();
			}
		} else {
			ColorTool.prototype.Ele.input[0].value = str;
			ColorTool.prototype.HexInput();
		}
		ColorTool.prototype.EventCollection();
	}


	ColorTool.prototype.hsbToRgb = function(hsb) {
		var rgb = {};
		var h = hsb.h;
		var s = hsb.s * 255 / 100;
		var v = hsb.b * 255 / 100;

		if (s == 0) {
			rgb.r = rgb.g = rgb.b = v;
		} else {
			var t1 = v;
			var t2 = (255 - s) * v / 255;
			var t3 = (t1 - t2) * (h % 60) / 60;
			if (h === 360) h = 0;
			if (h < 60) {
				rgb.r = t1;
				rgb.b = t2;
				rgb.g = t2 + t3
			} else if (h < 120) {
				rgb.g = t1;
				rgb.b = t2;
				rgb.r = t1 - t3
			} else if (h < 180) {
				rgb.g = t1;
				rgb.r = t2;
				rgb.b = t2 + t3
			} else if (h < 240) {
				rgb.b = t1;
				rgb.r = t2;
				rgb.g = t1 - t3
			} else if (h < 300) {
				rgb.b = t1;
				rgb.g = t2;
				rgb.r = t2 + t3
			} else if (h < 360) {
				rgb.r = t1;
				rgb.g = t2;
				rgb.b = t1 - t3
			} else {
				rgb.r = 0;
				rgb.g = 0;
				rgb.b = 0
			}
		}

		return {
			r: Math.round(rgb.r),
			g: Math.round(rgb.g),
			b: Math.round(rgb.b)
		};
	}

	ColorTool.prototype.rgbToHex = function(rgb) {
		var hex = [
			rgb.r.toString(16),
			rgb.g.toString(16),
			rgb.b.toString(16)
		];
		hex.map(function(str, i) {
			if (str.length == 1) {
				hex[i] = '0' + str;
			}
		});
		return hex.join('');
	}

	ColorTool.prototype.hexToRgb = function(hex) {
		var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
		return {
			r: hex >> 16,
			g: (hex & 0x00FF00) >> 8,
			b: (hex & 0x0000FF)
		};
	}

	ColorTool.prototype.hexToHsb = function(hex) {
		return this.rgbToHsb(this.hexToRgb(hex));
	}

	ColorTool.prototype.rgbToHsb = function(rgb) {
		var hsb = {
			h: 0,
			s: 0,
			b: 0
		};
		var min = Math.min(rgb.r, rgb.g, rgb.b);
		var max = Math.max(rgb.r, rgb.g, rgb.b);
		var delta = max - min;
		hsb.b = max;
		hsb.s = max != 0 ? 255 * delta / max : 0;
		if (hsb.s != 0) {
			if (rgb.r == max) hsb.h = (rgb.g - rgb.b) / delta;
			else if (rgb.g == max) hsb.h = 2 + (rgb.b - rgb.r) / delta;
			else hsb.h = 4 + (rgb.r - rgb.g) / delta;
		} else hsb.h = -1;
		hsb.h *= 60;
		if (hsb.h < 0) hsb.h += 360;
		hsb.s *= 100 / 255;
		hsb.b *= 100 / 255;
		return hsb;
	}

	ColorTool.prototype.rgbToHsl = function(rgb) {
		var HslArray = {
			h: rgb.r/255,
			s: rgb.g/255,
			l: rgb.b/255
		};

		var max = Math.max(HslArray.h, HslArray.s, HslArray.l);
		var min = Math.min(HslArray.h, HslArray.s, HslArray.l);
		var difference = max - min;


		var hsl = {h:0, s:0, l:0};

		if(max == min) {
			hsl.h = 0;
		} else if(max == HslArray.h && HslArray.s >= HslArray.l) {
			hsl.h = 60 * (HslArray.s - HslArray.l) / difference;
		} else if(max == HslArray.h && HslArray.s < HslArray.l) {
			hsl.h = 60 * (HslArray.s - HslArray.l) / difference + 360;
		} else if(max == HslArray.s) {
			hsl.h = 60 * (HslArray.l - HslArray.h) / difference + 120;
		} else if(max == HslArray.l) {
			hsl.h = 60 * (HslArray.h - HslArray.s) / difference + 240;
		}

		var sum = max + min;


		hsl.l = sum / 2;

		if(hsl.l == 0 || max == min) {
			hsl.s = 0;
		} else if(0 < hsl.l && hsl.l <= 0.5) {
			hsl.s = difference / sum;
		} else {
			hsl.s = difference / (2 - sum);
		}
		hsl.h = Math.round(hsl.h);
		return hsl;
	}

	ColorTool.prototype.hslToRgb = function(H = 0, S = 0, L = 0) {
		S /= 100;
		L /= 100;

		let CXM = {
			C:(1 - Math.abs(2 * L - 1)) * S,
			X:((1 - Math.abs(2 * L - 1)) * S) * (1 - Math.abs(((H / 60) % 2) - 1)),
			M:L - ((1 - Math.abs(2 * L - 1)) * S) / 2
		}

		let vRGB = []
		if (H >= 0 && H < 60) {
			vRGB.push(CXM.C, CXM.X, 0)
		} else if (H >= 60 && H < 120) {
			vRGB.push(CXM.X, CXM.C, 0)
		} else if (H >= 120 && H < 180) {
			vRGB.push(0, CXM.C, CXM.X)
		} else if (H >= 180 && H < 240) {
			vRGB.push(0, CXM.X, CXM.C)
		} else if (H >= 240 && H < 300) {
			vRGB.push(CXM.X, 0, CXM.C)
		} else if (H >= 300 && H < 360) {
			vRGB.push(CXM.C, 0, CXM.X)
		}
		const [vR, vG, vB] = vRGB
		let RGB = {
			r:Math.round(255 * (vR + CXM.M)),
			g:Math.round(255 * (vG + CXM.M)),
			b:Math.round(255 * (vB + CXM.M))
		}
		return RGB
	}

	ColorTool.prototype.setValue = function(rgb) {
		ColorTool.prototype.Ele.input[0].value = "#" + this.rgbToHex(rgb);
		ColorTool.prototype.Ele.input[1].value = rgb.r;
		ColorTool.prototype.Ele.input[2].value = rgb.g;
		ColorTool.prototype.Ele.input[3].value = rgb.b;
		let hsl = ColorTool.prototype.rgbToHsl(rgb);
		ColorTool.prototype.Ele.input[4].value = hsl.h;
		ColorTool.prototype.Ele.input[5].value = Math.round(hsl.s * 100) + "%";
		ColorTool.prototype.Ele.input[6].value = Math.round(hsl.l * 100) + "%";
	}

	ColorTool.prototype.changeColor = function() {
		let rgb = this.hsbToRgb(hsb);
		this.setValue(rgb);
		rgba.r = rgb.r;
		rgba.g = rgb.g;
		rgba.b = rgb.b;
		localStorage.setItem("ColorToolStorage","#" + this.rgbToHex(rgb));
		ColorTool.prototype.Ele.sample.style.backgroundColor = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b +
			',' + rgba.a + ')';
		clearTimeout(throttle);
		throttle = setTimeout(function() {
			if (ColorTool.prototype.thenFunExistence('rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')')) {
				ColorTool.prototype.then.prototype.thenFun('rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')');
			}
			clearTimeout(throttle);
		}, 36);
	}

	ColorTool.prototype.thenFunExistence = function(ColorData) {
		if (ColorTool.prototype.then.prototype.thenFun) {
			return true;
		} else {
			clearTimeout(setTime);
			setTime = setTimeout(function() { //延时防止调用thenFun时发生越界
				if (ColorTool.prototype.thenFunExistence(ColorData)) {
					ColorTool.prototype.then.prototype.thenFun(ColorData);
				}
				clearTimeout(setTime);
			}, 5);
		}
		return false;
	}

	ColorTool.prototype.PanelCalculation = function(x, y) {
		let MaxLeft = Math.max(0, Math.min(x, 216));
		let MaxTop = Math.max(0, Math.min(y, 124));
		hsb.s = 100 * MaxLeft / 216;
		hsb.b = 100 * (124 - MaxTop) / 124;
		this.changeColor();
	}

	ColorTool.prototype.PanelColor = function(ColorData){
		let canvas = ColorTool.prototype.Ele.panelCanvas;
		if(canvas && canvas.getContext){
			let ctx=canvas.getContext("2d");
	        // 底色填充,也就是(举例红色)到白色
			let gradientBase = ctx.createLinearGradient(3, 0, 216, 0);
			gradientBase.addColorStop(1, ColorData);
			gradientBase.addColorStop(0, "rgba(255,255,255,1)");
			ctx.fillStyle = gradientBase;
			ctx.fillRect(0, 0, 216, 124);
			// 第二次填充,黑色到透明
			let gradientScreen = ctx.createLinearGradient(0, 3, 0, 124);
			gradientScreen.addColorStop(0, "transparent");
			gradientScreen.addColorStop(1, "rgba(0,0,0,1)");
			ctx.fillStyle = gradientScreen;
			ctx.fillRect(0, 0, 216, 124);
		}
	}

	ColorTool.prototype.BarCalculation = function(x) {
		let Left = Math.max(0, Math.min(x, 216));
		hsb.h = 360 * Left / 216;
		let rgb = this.hsbToRgb({
			h: hsb.h,
			s: 100,
			b: 100
		});
		ColorTool.prototype.PanelColor('rgba(' + rgb.r + ',' + rgb.g + ',' +rgb.b + ',' + rgba.a + ')');
		this.changeColor();
		// rgba.a = X / elem_width;//调透明度的
	}

	ColorTool.prototype.panel = function(event) {
		ColorTool.prototype.Ele.DotOne.style.top = (event.offsetY - 7.5) + "px";
		ColorTool.prototype.Ele.DotOne.style.left = (event.offsetX - 7.5) + "px";
		ColorTool.prototype.PanelCalculation(event.offsetX, event.offsetY);
	}

	ColorTool.prototype.DiscolorationFun = function(event) {
		ColorTool.prototype.Ele.DotTwo.style.left = (event.offsetX - 7.5) + "px";
		ColorTool.prototype.BarCalculation(event.offsetX);
	}

	ColorTool.prototype.DotOneFun = function(event) {
		ColorTool.prototype.Ele.PanelContainer.removeEventListener("click", ColorTool.prototype.panel);
		let DotOneTop = event.offsetY > 0 ? event.offsetY : 0;
		let DotOneLeft = event.offsetX > 0 ? event.offsetX : 0;
		document.onmousemove = function(e) {
			e.preventDefault();
			let OneTop = e.clientY - (ColorTool.prototype.Ele.ColorToolContainer.offsetTop + DotOneTop);
			let OneLeft = e.clientX - (ColorTool.prototype.Ele.ColorToolContainer.offsetLeft +
				DotOneLeft);
				OneTop = OneTop <= -6 ? -6 : OneTop;
				OneTop = OneTop >= 115 ? 115 : OneTop;
				OneLeft = OneLeft <= -6 ? -6 : OneLeft;
				OneLeft = OneLeft >= 208 ? 208 : OneLeft;
			ColorTool.prototype.Ele.DotOne.style.top = OneTop + "px";
			ColorTool.prototype.Ele.DotOne.style.left = OneLeft + "px";
			ColorTool.prototype.PanelCalculation((e.clientX - ColorTool.prototype.Ele
				.ColorToolContainer.offsetLeft), (e
				.clientY - ColorTool.prototype.Ele.ColorToolContainer.offsetTop));
		}
		document.onmouseup = function(e) {
			document.onmousemove = null;
			document.onmouseup = null;
			let delayed = setTimeout(function() {
				ColorTool.prototype.Ele.PanelContainer.addEventListener('click', ColorTool.prototype
					.panel);
				clearTimeout(delayed);
			}, 10);
		}
	}

	ColorTool.prototype.DotTwoFun = function(event) {
		ColorTool.prototype.Ele.Discoloration.removeEventListener("click", ColorTool.prototype
			.DiscolorationFun);
		let DotTwoLeft = event.offsetX > 0 ? event.offsetX : 0;
		document.onmousemove = function(e) {
			e.preventDefault();
			let TwoLeft = e.clientX - (ColorTool.prototype.Ele.ColorToolContainer.offsetLeft +
				DotTwoLeft);
			TwoLeft = TwoLeft <= -7.5 ? -7.5 : TwoLeft;
			TwoLeft = TwoLeft >= 209.5 ? 209.5 : TwoLeft;
			ColorTool.prototype.Ele.DotTwo.style.left = TwoLeft + "px";
			ColorTool.prototype.BarCalculation(e.clientX - ColorTool.prototype.Ele.ColorToolContainer
				.offsetLeft);
		}
		document.onmouseup = function(e) {
			document.onmousemove = null;
			document.onmouseup = null;
			let delayed = setTimeout(function() {
				ColorTool.prototype.Ele.Discoloration.addEventListener('click', ColorTool
					.prototype.DiscolorationFun);
				clearTimeout(delayed);
			}, 10);
		}
	}

	ColorTool.prototype.setDistance = function(hsb) {
		ColorTool.prototype.Ele.DotOne.style.top = parseInt(((100 - hsb.b) * 124 / 100) - 7.5) + "px";
		ColorTool.prototype.Ele.DotOne.style.left = parseInt((hsb.s * 216 / 100) - 7.5) + "px";
		ColorTool.prototype.Ele.DotTwo.style.left = parseInt((hsb.h / 360 * 216) - 7.5) + "px";
		this.PanelCalculation(hsb.s * 216 / 100, (100 - hsb.b) * 124 / 100);
		this.BarCalculation(hsb.h / 360 * 216);
	}

	ColorTool.prototype.SpecialSymbol = function(str) {
		var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~!@#¥……&*()——|{}【】‘;:”“'。,、? ]");
		if (pattern.test(str)) {
			return true;
		}
		return false;
	}

	ColorTool.prototype.HexInput = function() {
		let ColorToolThis = ColorTool.prototype;
		if (!ColorTool.prototype.Ele.input[0].value) {
			alert('gun')
			return null;
		}
		if (ColorTool.prototype.Ele.input[0].value[0] !== "#") {
			ThisValuePro = "#" + ColorTool.prototype.Ele.input[0].value;
		} else {
			ThisValuePro = ColorTool.prototype.Ele.input[0].value.substring(1);
		}
		
		if (!ColorToolThis.SpecialSymbol(ThisValuePro)) {
			if (ThisValuePro.length === 6) {
				ColorToolThis.setDistance(ColorToolThis.hexToHsb(ColorTool.prototype.Ele.input[0].value));
			} else if (ThisValuePro.length === 3) {
				let NewValue = ThisValuePro[0] + ThisValuePro[0] + ThisValuePro[1] + ThisValuePro[1] +
					ThisValuePro[
						2] + ThisValuePro[2];
				ColorToolThis.setDistance(ColorToolThis.hexToHsb(NewValue));
			}
		}
	}

	ColorTool.prototype.RgbInput = function(event) {
		let ColorToolThis = ColorTool.prototype;
		if (!ColorToolThis.SpecialSymbol(ColorToolThis.Ele.input[1].value) && !ColorToolThis
			.SpecialSymbol(ColorToolThis.Ele.input[2].value) &&
			!ColorToolThis.SpecialSymbol(ColorToolThis.Ele.input[3].value)) {
			if (parseInt(ColorToolThis.Ele.input[1].value) >= 0 && parseInt(ColorToolThis.Ele.input[2]
					.value) >= 0 && parseInt(ColorToolThis.Ele.input[3].value) >=
				0) {
				if (parseInt(ColorToolThis.Ele.input[1].value) <= 255 && parseInt(ColorToolThis.Ele.input[2]
						.value) <= 255 && parseInt(ColorToolThis.Ele.input[3]
						.value) <=
					255) {
					ColorToolThis.setDistance(ColorToolThis.rgbToHsb({
						r: parseInt(ColorToolThis.Ele.input[1].value),
						g: parseInt(ColorToolThis.Ele.input[2].value),
						b: parseInt(ColorToolThis.Ele.input[3].value)
					}));
				}
			}
		}
		ColorTool.prototype.hslToRgb(0,100,50);
	}

	ColorTool.prototype.HslInput = function(event) {
		let ColorToolThis = ColorTool.prototype;
		if (!ColorToolThis.SpecialSymbol(ColorToolThis.Ele.input[4].value) && !ColorToolThis
			.SpecialSymbol(ColorToolThis.Ele.input[5].value) &&
			!ColorToolThis.SpecialSymbol(ColorToolThis.Ele.input[6].value)) {
			if (parseInt(ColorToolThis.Ele.input[4].value) >= 0 && parseInt(ColorToolThis.Ele.input[5]
					.value) >= 0 && parseInt(ColorToolThis.Ele.input[6].value) >=
				0) {
				if (parseInt(ColorToolThis.Ele.input[4].value) <= 360 && parseInt(ColorToolThis.Ele.input[5]
						.value) <= 100 && parseInt(ColorToolThis.Ele.input[6]
						.value) <=
					100) {
					ColorToolThis.setDistance(
						ColorToolThis.rgbToHsb(
							ColorTool.prototype.hslToRgb(
								parseInt(ColorToolThis.Ele.input[4].value),
								parseInt(ColorToolThis.Ele.input[5].value),
								parseInt(ColorToolThis.Ele.input[6].value)
							)
						)
					);
				}
			}
		}
	}

	ColorTool.prototype.NoneOrFlex = function(constant){
		ColorTool.prototype.Ele.InputBoxOne.style.display = "none";
		ColorTool.prototype.Ele.InputBoxTwo.style.display = "none";
		ColorTool.prototype.Ele.InputBoxThree.style.display = "none";
		if(constant === 0){
			ColorTool.prototype.Ele.InputBoxOne.style.display = "block";
		}else if(constant === 1){
			ColorTool.prototype.Ele.InputBoxTwo.style.display = "flex";
		}else{
			ColorTool.prototype.Ele.InputBoxThree.style.display = "flex";
		}
	}

	ColorTool.prototype.EventCollection = function() {
		ColorTool.prototype.Ele.PanelContainer.addEventListener('click', ColorTool.prototype.panel);
		ColorTool.prototype.Ele.Discoloration.addEventListener('click', ColorTool.prototype
			.DiscolorationFun);
		ColorTool.prototype.Ele.DotOne.addEventListener('mousedown', ColorTool.prototype.DotOneFun);
		ColorTool.prototype.Ele.DotTwo.addEventListener('mousedown', ColorTool.prototype.DotTwoFun);
		ColorTool.prototype.Ele.input[0].addEventListener('input', ColorTool.prototype.HexInput);
		ColorTool.prototype.Ele.input[1].addEventListener('input', ColorTool.prototype.RgbInput);
		ColorTool.prototype.Ele.input[2].addEventListener('input', ColorTool.prototype.RgbInput);
		ColorTool.prototype.Ele.input[3].addEventListener('input', ColorTool.prototype.RgbInput);
		ColorTool.prototype.Ele.input[4].addEventListener('input', ColorTool.prototype.HslInput);
		ColorTool.prototype.Ele.input[5].addEventListener('input', ColorTool.prototype.HslInput);
		ColorTool.prototype.Ele.input[6].addEventListener('input', ColorTool.prototype.HslInput);
		ColorTool.prototype.Ele.ControlButton.addEventListener('click', function() {
			ColorTool.prototype.init(Initial);
		});

		ColorTool.prototype.Ele.LeftAndRightlSpan[0].addEventListener('click', function() {
			ColorTool.prototype.Ele.constant = --ColorTool.prototype.Ele.constant >= 0 ? --ColorTool.prototype.Ele.constant : 1;
			ColorTool.prototype.NoneOrFlex(++ColorTool.prototype.Ele.constant);
		});
		ColorTool.prototype.Ele.LeftAndRightlSpan[1].addEventListener('click', function() {
			ColorTool.prototype.Ele.constant = ++ColorTool.prototype.Ele.constant <= 2 ? ++ColorTool.prototype.Ele.constant : 1;
			ColorTool.prototype.NoneOrFlex(--ColorTool.prototype.Ele.constant);
		});
	}

	event.ColorTool = ColorTool;
})(window);

以下是插件代码和配置

manifest.json

{
	"manifest_version": 3,
	"name": "ColorTool",
	"version": "1.0.0.003",
	"description": "这是一款没用的、简单的拾色器插件。",
	"icons": {
		"128": "logo/logo.png",
		"48": "logo/logo.png",
		"16": "logo/logo.png"
	},
	"action": {
		"default_popup": "popup.html",
		"default_icon": "logo/logo.png",
		"default_title": "ColorTool"
	},
	"minimum_chrome_version": "88.0",
	"options_page": "popup.html",
	"author": "我是知勤者笔记",
	"version_name": "ColorTool 1.0.0.003",
	"permissions": [
	    "contextMenus",
		"scripting",
		"activeTab"
	],
	"homepage_url": "https://blog.csdn.net/zhiqinzhe?type=blog",
	"background": {
	  "service_worker": "javascript/background.js"
	},
	"content_security_policy": {
		"extension_pages": "script-src 'self'; object-src 'self';"
	},
	"content_scripts": [
		{
			"matches": [
				"<all_urls>"
			  ],
			"css": ["icomoon/style.css","css/embedIndex.css"],
			"js": ["javascript/jquery.js","javascript/embedColorTool.js", "javascript/embedIndex.js"],
			"run_at": "document_idle",
			"all_frames": false
		}
	]
}

embedIndex.js

//创建页面函数
function createPage () {
    const CounterfeitBody = $('<div class="CounterfeitBody"></div>'),
        BodyMain = $('<div class="BodyMain"></div>'),
		sample=$('<div class="sample"></div>'),
        ColorToolContainer=$('<div class="ColorToolContainer"></div>'),
        PanelContainer=$('<div class="PanelContainer"></div>'),
		panelCanvas=$('<canvas id="panelCanvas" width="216" height="124">Your browser does not support canvas</canvas>'),
		DotOne=$('<div class="DotOne"></div>'),
        BarContainer=$('<div class="BarContainer"></div>'),
        Discoloration=$('<div class="Discoloration"></div>'),
        DotTwo=$('<div class="DotTwo"></div>'),
        other=$('<div class="other"></div>'),
		InputBoxContainer=$('<div class="InputBoxContainer"></div>'),
        InputBoxOne=$('<div class="InputBoxOne"></div>'),
		InputBoxOneinput=$('<input value="#ff0000" spellcheck="false" maxlength="7">'),
		InputBoxOnespan=$('<span>HEX(十六进制)</span>'),
        InputBoxTwo=$('<div class="InputBoxTwo"></div>'),
		InputBoxTwoDivR=$('<div></div>'),
        InputBoxTwoDivRinput=$('<input class="colorpicker-hexInput" value="255" maxlength="3" spellcheck="false">'),
        InputBoxTwoDivRspan=$('<span>r</span>'),
        InputBoxTwoDivG=$('<div></div>'),
        InputBoxTwoDivGinput=$('<input class="colorpicker-hexInput" value="0" maxlength="3" spellcheck="false">'),
        InputBoxTwoDivGspan=$('<span>g</span>'),
        InputBoxTwoDivB=$('<div></div>'),
        InputBoxTwoDivBinput=$('<input class="colorpicker-hexInput" value="0" maxlength="3" spellcheck="false">'),
        InputBoxTwoDivBspan=$('<span>b</span>'),
        InputBoxThree=$('<div class="InputBoxThree"></div>'),
        InputBoxThreeDivH=$('<div></div>'),
        InputBoxThreeDivHinput=$('<input class="colorpicker-hslInput" value="255" maxlength="4" spellcheck="false">'),
        InputBoxThreeDivHspan=$('<span>h</span>'),
        InputBoxThreeDivS=$('<div></div>'),
        InputBoxThreeDivSinput=$('<input class="colorpicker-hslInput" value="0" maxlength="4" spellcheck="false">'),
        InputBoxThreeDivSpan=$('<span>s</span>'),
        InputBoxThreeDivL=$('<div></div>'),
        InputBoxThreeDivLinput=$('<input class="colorpicker-hslInput" value="0" maxlength="4" spellcheck="false">'),
        InputBoxThreeDivLpan=$('<span>l</span>'),
        control=$('<div class="control"></div>'),
        controlbutton=$('<button>重置</button>'),
        LeftAndRight=$('<div class="LeftAndRight"></div>'),
        LeftAndRightleftspan=$('<span class="left"></span>'),
        LeftAndRightleftspani=$('<i><svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="1024" height="1024" viewBox="0 0 1024 1024"><style xmlns="http://www.w3.org/2000/svg" type="text/css">.st0{fill:#969696;}</style><g id="icomoon-ignore"></g><path xmlns="http://www.w3.org/2000/svg" class="st0" d="M768,63.2c0,0.1,0,0.3,0,0.4c0,16.5-6.2,31.5-16.4,42.9l0.1-0.1L405.2,494.8c-4,4.5-6.5,10.5-6.5,17  c0,6.5,2.5,12.5,6.5,17l0,0l346.4,388.4c10,11.4,16.2,26.4,16.2,42.9c0,20.9-9.9,39.5-25.2,51.4l-0.1,0.1c-10.3,7.5-23.3,12-37.3,12  c-19.5,0-36.9-8.7-48.6-22.4l-0.1-0.1L281.6,581.1c-16.5-18.3-26.5-42.6-26.5-69.2s10.1-51,26.6-69.3l-0.1,0.1L656.9,22.8  c11.9-13.9,29.4-22.6,48.9-22.6c15.1,0,29.1,5.2,40,14l-0.1-0.1C759.4,26,768,43.4,768,62.8C768,63,768,63.1,768,63.2L768,63.2  L768,63.2z"/></svg></i>'),
        LeftAndRightrightspan=$('<span class="right"></span>'),
        LeftAndRightrightspani=$('<i><svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="1024" height="1024" viewBox="0 0 1024 1024"><style xmlns="http://www.w3.org/2000/svg" type="text/css">.st0{fill:#969696;}</style><g id="icomoon-ignore"></g><path xmlns="http://www.w3.org/2000/svg" class="st0" d="M256,63.2c0,0.1,0,0.3,0,0.4c0,16.5,6.2,31.5,16.4,42.9l-0.1-0.1l346.4,388.4c4,4.5,6.5,10.5,6.5,17  c0,6.5-2.5,12.5-6.5,17l0,0L272.4,917.2c-10,11.4-16.2,26.4-16.2,42.9c0,20.9,9.9,39.5,25.2,51.4l0.1,0.1c10.4,7.5,23.3,12,37.3,12  c19.5,0,36.9-8.7,48.6-22.4l0.1-0.1l374.8-420.1c16.5-18.3,26.5-42.6,26.5-69.2s-10.1-51-26.6-69.3l0.1,0.1L367.1,22.8  C355.2,8.9,337.7,0.2,318.2,0.2c-15.1,0-29.1,5.2-40,14l0.1-0.1C264.6,26,256,43.4,256,62.8C256,63,256,63.1,256,63.2L256,63.2  L256,63.2z"/></svg></i>'),
        getColor=$('<button class="getColor">吸取颜色</button>'),
        MSclose=$('<button class="MSclose">收起来</button>');
        CounterfeitBody.append(BodyMain);
        BodyMain.append(sample);
        PanelContainer.append(DotOne);
        PanelContainer.append(panelCanvas);
        ColorToolContainer.append(PanelContainer);
        Discoloration.append(DotTwo);
        BarContainer.append(Discoloration);
		ColorToolContainer.append(BarContainer);
		InputBoxOne.append(InputBoxOneinput);
		InputBoxOne.append(InputBoxOnespan);
		InputBoxContainer.append(InputBoxOne);
        InputBoxTwoDivR.append(InputBoxTwoDivRinput);
        InputBoxTwoDivR.append(InputBoxTwoDivRspan);
        InputBoxTwo.append(InputBoxTwoDivR);
        InputBoxTwoDivG.append(InputBoxTwoDivGinput);
        InputBoxTwoDivG.append(InputBoxTwoDivGspan);
        InputBoxTwo.append(InputBoxTwoDivG);
        InputBoxTwoDivB.append(InputBoxTwoDivBinput);
        InputBoxTwoDivB.append(InputBoxTwoDivBspan);
        InputBoxTwo.append(InputBoxTwoDivB);		
        InputBoxContainer.append(InputBoxTwo);
        InputBoxThreeDivH.append(InputBoxThreeDivHinput);
        InputBoxThreeDivH.append(InputBoxThreeDivHspan);
        InputBoxThree.append(InputBoxThreeDivH);
        InputBoxThreeDivS.append(InputBoxThreeDivSinput);
        InputBoxThreeDivS.append(InputBoxThreeDivSpan);
        InputBoxThree.append(InputBoxThreeDivS);
        InputBoxThreeDivL.append(InputBoxThreeDivLinput);
        InputBoxThreeDivL.append(InputBoxThreeDivLpan);
        InputBoxThree.append(InputBoxThreeDivL);
        InputBoxContainer.append(InputBoxThree);
        other.append(InputBoxContainer);
        control.append(controlbutton);
        LeftAndRightleftspan.append(LeftAndRightleftspani);
        LeftAndRight.append(LeftAndRightleftspan);
        LeftAndRightrightspan.append(LeftAndRightrightspani);
        LeftAndRight.append(LeftAndRightrightspan);
        control.append(LeftAndRight);
        other.append(control);
        ColorToolContainer.append(other);
        BodyMain.append(ColorToolContainer);
        BodyMain.append(getColor);
        BodyMain.append(MSclose);
        const NewDiv =$('<div class="NewDiv">拾取颜色</div>');
    $('body').append(CounterfeitBody);
    $('body').append(NewDiv);

    const colorData = localStorage.getItem("ColorToolStorage") || "#008CD6";

    ColorTool(colorData).then(function(ColorData){});
    //拖拽
    drag();
}
createPage();

$('.NewDiv').click(function(){
    $('.CounterfeitBody').css('display','block');
    $('.NewDiv').css('display','none');
});

$('.MSclose').click(function(){
    $('.NewDiv').css('display','block');
    $('.CounterfeitBody').css('display','none');
});

//拖拽
function drag(e) {
    let oldX, oldY, newX, newY,
    sampleEle = document.querySelector('.sample'),
    CounterfeitBodyEle = document.querySelector('.CounterfeitBody');
    sampleEle.onmousedown = function (e) {
        if (!CounterfeitBodyEle.style.right && !CounterfeitBodyEle.style.bottom) {
            CounterfeitBodyEle.style.right = 0
            CounterfeitBodyEle.style.bottom = 0
        }
        oldX = e.clientX
        oldY = e.clientY
        document.onmousemove = function (e) {
            newX = e.clientX
            newY = e.clientY
            CounterfeitBodyEle.style.right = parseInt(CounterfeitBodyEle.style.right) - newX + oldX + 'px'
            CounterfeitBodyEle.style.bottom = parseInt(CounterfeitBodyEle.style.bottom) - newY + oldY + 'px'
            oldX = newX
            oldY = newY
        }
        document.onmouseup = function () {
            document.onmousemove = null
            document.onmouseup = null
        }
    }
}

embedColorTool.js

(function(event) {
	event = event || document;
	let rgba = {
			r: 0,
			g: 0,
			b: 0,
			a: 1
		},
		hsb = {
			h: 0,
			s: 100,
			b: 100
		};

	let Initial = null,
		setTime = null,
		throttle = null;

	function ColorTool(str) {
		ColorTool.prototype.Ele = {
            CounterfeitBody: document.querySelector('.CounterfeitBody'),
			sample: document.querySelector('.CounterfeitBody .sample'),
			ColorToolContainer: document.querySelector('.ColorToolContainer'),
			PanelContainer: document.querySelector('.CounterfeitBody .PanelContainer'),
			panelCanvas: document.querySelector('.CounterfeitBody #panelCanvas'),
			DotOne: document.querySelector('.CounterfeitBody .DotOne'),
			Discoloration: document.querySelector('.CounterfeitBody .Discoloration'),
			DotTwo: document.querySelector('.CounterfeitBody .DotTwo'),
			input: document.querySelectorAll('.CounterfeitBody input'),
			ControlButton: document.querySelector('.CounterfeitBody .control>button'),
			LeftAndRightlSpan: document.querySelectorAll('.CounterfeitBody .LeftAndRight>span'),
			InputBoxOne: document.querySelector('.CounterfeitBody .InputBoxOne'),
			InputBoxTwo: document.querySelector('.CounterfeitBody .InputBoxTwo'),
			InputBoxThree: document.querySelector('.CounterfeitBody .InputBoxThree'),
			getColor: document.querySelector(".CounterfeitBody .getColor"),
			constant:0
		};
		Initial = str;
		return new ColorTool.prototype.init(str);
	}
	ColorTool.prototype.init = function(str) {
		ColorTool.prototype.initANDsetColor(str);
		ColorTool.prototype.getColorFun();
		return this;
	}

	ColorTool.prototype.init.prototype = ColorTool.prototype;

	ColorTool.prototype.then = function(parameter) {
		ColorTool.prototype.then.prototype.thenFun = parameter;
	}

	ColorTool.setColor = function(str) {
		if (ColorTool.prototype.initANDsetColor) {
			ColorTool.prototype.initANDsetColor(str);
		} else {
			throw new Error('未调用ColorTool函数');
		}
	}
	
	ColorTool.prototype.getColorFun = function() {
		if ('EyeDropper' in window) { // 判断是否支持这个api
		  let eyeDropper = new EyeDropper(); // 创建对象
		  ColorTool.prototype.Ele.getColor.addEventListener('click', async () => { 
		    try {
		      const ColorResult = await eyeDropper.open();// 取得吸取结果
		      ColorTool.setColor(ColorResult.sRGBHex);// 取得颜色并设置颜色
		    } catch (e) {
		      console.warn('你取消了取色操作')
		    }
		  });
		}
	}

	ColorTool.prototype.initANDsetColor = function(str) {
		if (str.match(/rgb\(|\Rgb\(/g) && str.match(/\)|\);/g) && str.match(/,/g)) {
			if (str.match(/,/g).length === 2) {
				str = str.replace(/rgb\(|\Rgb\(/g, '').replace(/\)|\);/g, '');
				let strArr = str.split(',');
				ColorTool.prototype.Ele.input[1].value = parseInt(strArr[0]);
				ColorTool.prototype.Ele.input[2].value = parseInt(strArr[1]);
				ColorTool.prototype.Ele.input[3].value = parseInt(strArr[2]);
				ColorTool.prototype.RgbInput();
			}
		} else {
			ColorTool.prototype.Ele.input[0].value = str;
			ColorTool.prototype.HexInput();
		}
		ColorTool.prototype.EventCollection();
	}


	ColorTool.prototype.hsbToRgb = function(hsb) {
		var rgb = {};
		var h = hsb.h;
		var s = hsb.s * 255 / 100;
		var v = hsb.b * 255 / 100;

		if (s == 0) {
			rgb.r = rgb.g = rgb.b = v;
		} else {
			var t1 = v;
			var t2 = (255 - s) * v / 255;
			var t3 = (t1 - t2) * (h % 60) / 60;
			if (h === 360) h = 0;
			if (h < 60) {
				rgb.r = t1;
				rgb.b = t2;
				rgb.g = t2 + t3
			} else if (h < 120) {
				rgb.g = t1;
				rgb.b = t2;
				rgb.r = t1 - t3
			} else if (h < 180) {
				rgb.g = t1;
				rgb.r = t2;
				rgb.b = t2 + t3
			} else if (h < 240) {
				rgb.b = t1;
				rgb.r = t2;
				rgb.g = t1 - t3
			} else if (h < 300) {
				rgb.b = t1;
				rgb.g = t2;
				rgb.r = t2 + t3
			} else if (h < 360) {
				rgb.r = t1;
				rgb.g = t2;
				rgb.b = t1 - t3
			} else {
				rgb.r = 0;
				rgb.g = 0;
				rgb.b = 0
			}
		}

		return {
			r: Math.round(rgb.r),
			g: Math.round(rgb.g),
			b: Math.round(rgb.b)
		};
	}

	ColorTool.prototype.rgbToHex = function(rgb) {
		var hex = [
			rgb.r.toString(16),
			rgb.g.toString(16),
			rgb.b.toString(16)
		];
		hex.map(function(str, i) {
			if (str.length == 1) {
				hex[i] = '0' + str;
			}
		});
		return hex.join('');
	}

	ColorTool.prototype.hexToRgb = function(hex) {
		var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
		return {
			r: hex >> 16,
			g: (hex & 0x00FF00) >> 8,
			b: (hex & 0x0000FF)
		};
	}

	ColorTool.prototype.hexToHsb = function(hex) {
		return this.rgbToHsb(this.hexToRgb(hex));
	}

	ColorTool.prototype.rgbToHsb = function(rgb) {
		var hsb = {
			h: 0,
			s: 0,
			b: 0
		};
		var min = Math.min(rgb.r, rgb.g, rgb.b);
		var max = Math.max(rgb.r, rgb.g, rgb.b);
		var delta = max - min;
		hsb.b = max;
		hsb.s = max != 0 ? 255 * delta / max : 0;
		if (hsb.s != 0) {
			if (rgb.r == max) hsb.h = (rgb.g - rgb.b) / delta;
			else if (rgb.g == max) hsb.h = 2 + (rgb.b - rgb.r) / delta;
			else hsb.h = 4 + (rgb.r - rgb.g) / delta;
		} else hsb.h = -1;
		hsb.h *= 60;
		if (hsb.h < 0) hsb.h += 360;
		hsb.s *= 100 / 255;
		hsb.b *= 100 / 255;
		return hsb;
	}

    ColorTool.prototype.rgbToHsl = function(rgb) {
		var HslArray = {
			h: rgb.r/255,
			s: rgb.g/255,
			l: rgb.b/255
		};

		var max = Math.max(HslArray.h, HslArray.s, HslArray.l);
		var min = Math.min(HslArray.h, HslArray.s, HslArray.l);
		var difference = max - min;


		var hsl = {h:0, s:0, l:0};

		if(max == min) {
			hsl.h = 0;
		} else if(max == HslArray.h && HslArray.s >= HslArray.l) {
			hsl.h = 60 * (HslArray.s - HslArray.l) / difference;
		} else if(max == HslArray.h && HslArray.s < HslArray.l) {
			hsl.h = 60 * (HslArray.s - HslArray.l) / difference + 360;
		} else if(max == HslArray.s) {
			hsl.h = 60 * (HslArray.l - HslArray.h) / difference + 120;
		} else if(max == HslArray.l) {
			hsl.h = 60 * (HslArray.h - HslArray.s) / difference + 240;
		}

		var sum = max + min;


		hsl.l = sum / 2;

		if(hsl.l == 0 || max == min) {
			hsl.s = 0;
		} else if(0 < hsl.l && hsl.l <= 0.5) {
			hsl.s = difference / sum;
		} else {
			hsl.s = difference / (2 - sum);
		}
		hsl.h = Math.round(hsl.h);
		return hsl;
	}

	ColorTool.prototype.hslToRgb = function(H = 0, S = 0, L = 0) {
		S /= 100;
		L /= 100;

		let CXM = {
			C:(1 - Math.abs(2 * L - 1)) * S,
			X:((1 - Math.abs(2 * L - 1)) * S) * (1 - Math.abs(((H / 60) % 2) - 1)),
			M:L - ((1 - Math.abs(2 * L - 1)) * S) / 2
		}

		let vRGB = []
		if (H >= 0 && H < 60) {
			vRGB.push(CXM.C, CXM.X, 0)
		} else if (H >= 60 && H < 120) {
			vRGB.push(CXM.X, CXM.C, 0)
		} else if (H >= 120 && H < 180) {
			vRGB.push(0, CXM.C, CXM.X)
		} else if (H >= 180 && H < 240) {
			vRGB.push(0, CXM.X, CXM.C)
		} else if (H >= 240 && H < 300) {
			vRGB.push(CXM.X, 0, CXM.C)
		} else if (H >= 300 && H < 360) {
			vRGB.push(CXM.C, 0, CXM.X)
		}
		const [vR, vG, vB] = vRGB
		let RGB = {
			r:Math.round(255 * (vR + CXM.M)),
			g:Math.round(255 * (vG + CXM.M)),
			b:Math.round(255 * (vB + CXM.M))
		}
		return RGB
	}

	ColorTool.prototype.setValue = function(rgb) {
		ColorTool.prototype.Ele.input[0].value = "#" + this.rgbToHex(rgb);
		ColorTool.prototype.Ele.input[1].value = rgb.r;
		ColorTool.prototype.Ele.input[2].value = rgb.g;
		ColorTool.prototype.Ele.input[3].value = rgb.b;
		let hsl = ColorTool.prototype.rgbToHsl(rgb);
		ColorTool.prototype.Ele.input[4].value = hsl.h;
		ColorTool.prototype.Ele.input[5].value = Math.round(hsl.s * 100) + "%";
		ColorTool.prototype.Ele.input[6].value = Math.round(hsl.l * 100) + "%";
	}

	ColorTool.prototype.changeColor = function() {
		let rgb = this.hsbToRgb(hsb);
		this.setValue(rgb);
		rgba.r = rgb.r;
		rgba.g = rgb.g;
		rgba.b = rgb.b;
		localStorage.setItem("ColorToolStorage","#" + this.rgbToHex(rgb));
		ColorTool.prototype.Ele.sample.style.backgroundColor = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b +
			',' + rgba.a + ')';
		if(!(rgb.r >= 196 && rgb.g >= 196 && rgb.b >= 196)){
			document.documentElement.style.setProperty('--MyColor', 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b +',' + rgba.a + ')');
		}

		clearTimeout(throttle);
		throttle = setTimeout(function() {
			if (ColorTool.prototype.thenFunExistence('rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')')) {
				ColorTool.prototype.then.prototype.thenFun('rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')');
			}
			clearTimeout(throttle);
		}, 36);
	}

	ColorTool.prototype.thenFunExistence = function(ColorData) {
		if (ColorTool.prototype.then.prototype.thenFun) {
			return true;
		} else {
			clearTimeout(setTime);
			setTime = setTimeout(function() { //延时防止调用thenFun时发生越界
				if (ColorTool.prototype.thenFunExistence(ColorData)) {
					ColorTool.prototype.then.prototype.thenFun(ColorData);
				}
				clearTimeout(setTime);
			}, 5);
		}
		return false;
	}

	ColorTool.prototype.PanelCalculation = function(x, y) {
		let MaxLeft = Math.max(0, Math.min(x, 216));
		let MaxTop = Math.max(0, Math.min(y, 124));
		hsb.s = 100 * MaxLeft / 216;
		hsb.b = 100 * (124 - MaxTop) / 124;
		this.changeColor();
	}

    ColorTool.prototype.PanelColor = function(ColorData){
		let canvas = ColorTool.prototype.Ele.panelCanvas;
		if(canvas && canvas.getContext){
			let ctx=canvas.getContext("2d");
	        // 底色填充,也就是(举例红色)到白色
			let gradientBase = ctx.createLinearGradient(3, 0, 216, 0);
			gradientBase.addColorStop(1, ColorData);
			gradientBase.addColorStop(0, "rgba(255,255,255,1)");
			ctx.fillStyle = gradientBase;
			ctx.fillRect(0, 0, 216, 124);
			// 第二次填充,黑色到透明
			let gradientScreen = ctx.createLinearGradient(0, 3, 0, 124);
			gradientScreen.addColorStop(0, "transparent");
			gradientScreen.addColorStop(1, "rgba(0,0,0,1)");
			ctx.fillStyle = gradientScreen;
			ctx.fillRect(0, 0, 216, 124);
		}
	}

	ColorTool.prototype.BarCalculation = function(x) {
		let Left = Math.max(0, Math.min(x, 216));
		hsb.h = 360 * Left / 216;
		let rgb = this.hsbToRgb({
			h: hsb.h,
			s: 100,
			b: 100
		});
		ColorTool.prototype.PanelColor('rgba(' + rgb.r + ',' + rgb.g + ',' +rgb.b + ',' + rgba.a + ')');
		this.changeColor();
		// rgba.a = X / elem_width;//调透明度的
	}

	ColorTool.prototype.panel = function(event) {
		ColorTool.prototype.Ele.DotOne.style.top = (event.offsetY - 7.5) + "px";
		ColorTool.prototype.Ele.DotOne.style.left = (event.offsetX - 7.5) + "px";
		ColorTool.prototype.PanelCalculation(event.offsetX, event.offsetY);
	}

	ColorTool.prototype.DiscolorationFun = function(event) {
		ColorTool.prototype.Ele.DotTwo.style.left = (event.offsetX - 7.5) + "px";
		ColorTool.prototype.BarCalculation(event.offsetX);
	}

	ColorTool.prototype.DotOneFun = function(event) {
		ColorTool.prototype.Ele.PanelContainer.removeEventListener("click", ColorTool.prototype.panel);
		let CounterfeitBodyTop = ColorTool.prototype.Ele.CounterfeitBody.offsetTop;
		let CounterfeitBodyLeft = ColorTool.prototype.Ele.CounterfeitBody.offsetLeft;
		let DotOneTop = event.offsetY > 0 ? event.offsetY : 0;
		let DotOneLeft = event.offsetX > 0 ? event.offsetX : 0;
		document.onmousemove = function(e) {
			e.preventDefault();
			let OneTop = e.clientY - (CounterfeitBodyTop + ColorTool.prototype.Ele.ColorToolContainer.offsetTop + DotOneTop*1.5);
			let OneLeft = e.clientX - (CounterfeitBodyLeft + ColorTool.prototype.Ele.ColorToolContainer.offsetLeft +
				DotOneLeft*1.5);
				OneTop = OneTop <= -6 ? -6 : OneTop;
				OneTop = OneTop >= 115 ? 115 : OneTop;
				OneLeft = OneLeft <= -6 ? -6 : OneLeft;
				OneLeft = OneLeft >= 208 ? 208 : OneLeft;
			ColorTool.prototype.Ele.DotOne.style.top = OneTop + "px";
			ColorTool.prototype.Ele.DotOne.style.left = OneLeft + "px";
			ColorTool.prototype.PanelCalculation((e.clientX - (CounterfeitBodyLeft + ColorTool.prototype.Ele.ColorToolContainer.offsetLeft)), (e.clientY - (CounterfeitBodyTop + ColorTool.prototype.Ele.ColorToolContainer.offsetTop)));
		}
		document.onmouseup = function(e) {
			document.onmousemove = null;
			document.onmouseup = null;
			let delayed = setTimeout(function() {
				ColorTool.prototype.Ele.PanelContainer.addEventListener('click', ColorTool.prototype
					.panel);
				clearTimeout(delayed);
			}, 10);
		}
	}

	ColorTool.prototype.DotTwoFun = function(event) {
		ColorTool.prototype.Ele.Discoloration.removeEventListener("click", ColorTool.prototype
			.DiscolorationFun);
		let CounterfeitBodyLeft = ColorTool.prototype.Ele.CounterfeitBody.offsetLeft;
		let DotTwoLeft = event.offsetX > 0 ? event.offsetX : 0;
		document.onmousemove = function(e) {
			e.preventDefault();
			let TwoLeft = e.clientX - (CounterfeitBodyLeft + ColorTool.prototype.Ele.ColorToolContainer.offsetLeft +
				DotTwoLeft);
			TwoLeft = TwoLeft <= -7.5 ? -7.5 : TwoLeft;
			TwoLeft = TwoLeft >= 209.5 ? 209.5 : TwoLeft;
			ColorTool.prototype.Ele.DotTwo.style.left = TwoLeft + "px";
			ColorTool.prototype.BarCalculation(e.clientX - (CounterfeitBodyLeft + ColorTool.prototype.Ele.ColorToolContainer.offsetLeft));
		}
		document.onmouseup = function(e) {
			document.onmousemove = null;
			document.onmouseup = null;
			let delayed = setTimeout(function() {
				ColorTool.prototype.Ele.Discoloration.addEventListener('click', ColorTool
					.prototype.DiscolorationFun);
				clearTimeout(delayed);
			}, 10);
		}
	}

	ColorTool.prototype.setDistance = function(hsb) {
		ColorTool.prototype.Ele.DotOne.style.top = parseInt(((100 - hsb.b) * 124 / 100) - 7.5) + "px";
		ColorTool.prototype.Ele.DotOne.style.left = parseInt((hsb.s * 216 / 100) - 7.5) + "px";
		ColorTool.prototype.Ele.DotTwo.style.left = parseInt((hsb.h / 360 * 216) - 7.5) + "px";
		this.PanelCalculation(hsb.s * 216 / 100, (100 - hsb.b) * 124 / 100);
		this.BarCalculation(hsb.h / 360 * 216);
	}

	ColorTool.prototype.SpecialSymbol = function(str) {
		var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~!@#¥……&*()——|{}【】‘;:”“'。,、? ]");
		if (pattern.test(str)) {
			return true;
		}
		return false;
	}

	ColorTool.prototype.HexInput = function() {
		let ColorToolThis = ColorTool.prototype;
		if (!ColorTool.prototype.Ele.input[0].value) {
			return null;
		}
		if (ColorTool.prototype.Ele.input[0].value[0] !== "#") {
			ThisValuePro = "#" + ColorTool.prototype.Ele.input[0].value;
		} else {
			ThisValuePro = ColorTool.prototype.Ele.input[0].value.substring(1);
		}
		if (!ColorToolThis.SpecialSymbol(ThisValuePro)) {
			if (ThisValuePro.length === 6) {
				ColorToolThis.setDistance(ColorToolThis.hexToHsb(ColorTool.prototype.Ele.input[0].value));
			} else if (ThisValuePro.length === 3) {
				let NewValue = ThisValuePro[0] + ThisValuePro[0] + ThisValuePro[1] + ThisValuePro[1] +
					ThisValuePro[
						2] + ThisValuePro[2];
				ColorToolThis.setDistance(ColorToolThis.hexToHsb(NewValue));
			}
		}
	}

	ColorTool.prototype.RgbInput = function(event) {
		let ColorToolThis = ColorTool.prototype;
		if (!ColorToolThis.SpecialSymbol(ColorToolThis.Ele.input[1].value) && !ColorToolThis
			.SpecialSymbol(ColorToolThis.Ele.input[2].value) &&
			!ColorToolThis.SpecialSymbol(ColorToolThis.Ele.input[3].value)) {
			if (parseInt(ColorToolThis.Ele.input[1].value) >= 0 && parseInt(ColorToolThis.Ele.input[2]
					.value) >= 0 && parseInt(ColorToolThis.Ele.input[3].value) >=
				0) {
				if (parseInt(ColorToolThis.Ele.input[1].value) <= 255 && parseInt(ColorToolThis.Ele.input[2]
						.value) <= 255 && parseInt(ColorToolThis.Ele.input[3]
						.value) <=
					255) {
					ColorToolThis.setDistance(ColorToolThis.rgbToHsb({
						r: parseInt(ColorToolThis.Ele.input[1].value),
						g: parseInt(ColorToolThis.Ele.input[2].value),
						b: parseInt(ColorToolThis.Ele.input[3].value)
					}));
				}
			}
		}
	}

    ColorTool.prototype.HslInput = function(event) {
		let ColorToolThis = ColorTool.prototype;
		if (!ColorToolThis.SpecialSymbol(ColorToolThis.Ele.input[4].value) && !ColorToolThis
			.SpecialSymbol(ColorToolThis.Ele.input[5].value) &&
			!ColorToolThis.SpecialSymbol(ColorToolThis.Ele.input[6].value)) {
			if (parseInt(ColorToolThis.Ele.input[4].value) >= 0 && parseInt(ColorToolThis.Ele.input[5]
					.value) >= 0 && parseInt(ColorToolThis.Ele.input[6].value) >=
				0) {
				if (parseInt(ColorToolThis.Ele.input[4].value) <= 360 && parseInt(ColorToolThis.Ele.input[5]
						.value) <= 100 && parseInt(ColorToolThis.Ele.input[6]
						.value) <=
					100) {
					ColorToolThis.setDistance(
						ColorToolThis.rgbToHsb(
							ColorTool.prototype.hslToRgb(
								parseInt(ColorToolThis.Ele.input[4].value),
								parseInt(ColorToolThis.Ele.input[5].value),
								parseInt(ColorToolThis.Ele.input[6].value)
							)
						)
					);
				}
			}
		}
	}

    ColorTool.prototype.NoneOrFlex = function(constant){
		ColorTool.prototype.Ele.InputBoxOne.style.display = "none";
		ColorTool.prototype.Ele.InputBoxTwo.style.display = "none";
		ColorTool.prototype.Ele.InputBoxThree.style.display = "none";
		if(constant === 0){
			ColorTool.prototype.Ele.InputBoxOne.style.display = "block";
		}else if(constant === 1){
			ColorTool.prototype.Ele.InputBoxTwo.style.display = "flex";
		}else{
			ColorTool.prototype.Ele.InputBoxThree.style.display = "flex";
		}
	}

	ColorTool.prototype.EventCollection = function() {
		ColorTool.prototype.Ele.PanelContainer.addEventListener('click', ColorTool.prototype.panel);
		ColorTool.prototype.Ele.Discoloration.addEventListener('click', ColorTool.prototype
			.DiscolorationFun);
		ColorTool.prototype.Ele.DotOne.addEventListener('mousedown', ColorTool.prototype.DotOneFun);
		ColorTool.prototype.Ele.DotTwo.addEventListener('mousedown', ColorTool.prototype.DotTwoFun);
		ColorTool.prototype.Ele.input[0].addEventListener('', ColorTool.prototype.HexInput);
		ColorTool.prototype.Ele.input[1].addEventListener('input', ColorTool.prototype.RgbInput);
		ColorTool.prototype.Ele.input[2].addEventListener('input', ColorTool.prototype.RgbInput);
		ColorTool.prototype.Ele.input[3].addEventListener('input', ColorTool.prototype.RgbInput);
        ColorTool.prototype.Ele.input[4].addEventListener('input', ColorTool.prototype.HslInput);
		ColorTool.prototype.Ele.input[5].addEventListener('input', ColorTool.prototype.HslInput);
		ColorTool.prototype.Ele.input[6].addEventListener('input', ColorTool.prototype.HslInput);
		ColorTool.prototype.Ele.ControlButton.addEventListener('click', function() {
			ColorTool.prototype.init(Initial);
		});

		ColorTool.prototype.Ele.LeftAndRightlSpan[0].addEventListener('click', function() {
			ColorTool.prototype.Ele.constant = --ColorTool.prototype.Ele.constant >= 0 ? --ColorTool.prototype.Ele.constant : 1;
			ColorTool.prototype.NoneOrFlex(++ColorTool.prototype.Ele.constant);
		});
		ColorTool.prototype.Ele.LeftAndRightlSpan[1].addEventListener('click', function() {
			ColorTool.prototype.Ele.constant = ++ColorTool.prototype.Ele.constant <= 2 ? ++ColorTool.prototype.Ele.constant : 1;
			ColorTool.prototype.NoneOrFlex(--ColorTool.prototype.Ele.constant);
		});
	}

	event.ColorTool = ColorTool;
})(window);

background.js

chrome.contextMenus.create({
    "id" : "ColorTool",
    "title": "获取颜色",
    "contexts": ["all"]
});

function EjectNewDiv(){
	// console.log(ColorTool.setColor);
	if(document.querySelector('.NewDiv')){
		document.querySelector('.NewDiv').click();
		let setTime = setTimeout(function() {
			if(document.querySelector('.getColor')){
				document.querySelector('.getColor').click();
			}
			clearTimeout(setTime);
		}, 12);
	}
}

chrome.contextMenus.onClicked.addListener(function(clickData){
	chrome.tabs.query({
		currentWindow: true,
		active: true
	}, function (tabs) {
		chrome.scripting.executeScript({
			      target: { tabId: tabs[0].id },
			      function:EjectNewDiv
			    });
		// chrome.scripting.executeScript({
		// 	      target: { tabId: tabs[0].id },
		// 	      files:['javascript/excute.js']
		// 	    });
	});
});

chrome.runtime.onInstalled.addListener(() => {
    // 清除插件所有的本地数据
    chrome.storage.local.clear();
    // 设置初始数据
    chrome.storage.local.set({
        "ColorToolStorage": "#008cd6"
    }, function () {
        console.log("chrome extension is install.");
    });
});

安装

你可以把它下载解压后拖拽到浏览器的扩展选项安装成扩展使用

可以到这里下载icon-default.png?t=N7T8https://download.csdn.net/download/zhiqinzhe/86783066

还可以到这里下载icon-default.png?t=N7T8https://gitee.com/zhiqinzhe/zhiqinzheblog/tree/master/ObtainColor

兼容性

不兼容IE10以下的浏览器和火狐浏览器,不兼容IE10浏览器(语法方面不兼容可以简单修改达到100%兼容),EyeDropper(浏览器api)兼容性如下:

版权说明

颜色和各种颜色值之间的转换算法借鉴于简书平台,上传资源距编写之时已5个多月,忘记算法原作者是哪位了;其他均由本人所写。

  • 10
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知勤者笔记

给点吧,没动力了!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值