chrome95版本以后新增EyeDropper api支持通过js来获取电脑屏幕任意位置的颜色值了,示例代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum=1.0,minimum=1.0,user-scalable=0" /> <title>BFW NEW PAGE</title> <style> .preview { height: 30px; border-radius: 15px; width: 30px; display: block; float: left; } </style> </head> <body> <div class="output"> <span class="preview"></span> <input type="text" class="color"> <button class="getColor">点击取色</button> </div> <script> if (!window.EyeDropper) { window.pre.innerHTML = "需要Chrome 95以上才支持屏幕取色"; } const getColor = async e => { const eyeDropper = new EyeDropper(); try { const { sRGBHex } = await eyeDropper.open(); document.querySelector('.preview'). style.background = sRGBHex; document.querySelector('.color').value = sRGBHex; } catch (e) { document.querySelector('.color').value = '出错了'; } }; // Click binding document.querySelector(".getColor"). addEventListener("click", getColor); </script> </body> </html>
网友回复