求全浏览器兼容的EyeDropper API PolyFill书签工具
跨浏览器取色书签工具(Polyfill方案)
以下是兼容所有主流浏览器的取色书签代码,替代仅支持Chromium的EyeDropper API,满足你从窗口选像素并以十六进制alert结果的需求:
javascript:(function(){ // 创建全屏canvas捕获页面 const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const body = document.body; canvas.width = window.innerWidth; canvas.height = window.innerHeight; canvas.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;cursor:crosshair;z-index:999999;background:rgba(0,0,0,0.1);'; // 绘制页面到canvas(兼容多浏览器的快照逻辑) try { ctx.drawWindow(window, 0, 0, canvas.width, canvas.height, 'rgb(255,255,255)'); } catch(e) { // 针对不支持drawWindow的浏览器,用截图API降级处理(若可用) if(window.navigator.mediaDevices && window.navigator.mediaDevices.getDisplayMedia) { window.navigator.mediaDevices.getDisplayMedia({video: {displaySurface: 'browser'}}) .then(stream => { const video = document.createElement('video'); video.srcObject = stream; video.onloadedmetadata = () => { ctx.drawImage(video, 0, 0, canvas.width, canvas.height); stream.getTracks()[0].stop(); }; }); } } // 创建遮罩提示层 const overlay = document.createElement('div'); overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;display:flex;align-items:center;justify-content:center;color:white;font-size:18px;pointer-events:none;z-index:9999999;'; overlay.textContent = '点击选取像素颜色'; // 添加元素到页面 body.appendChild(canvas); body.appendChild(overlay); // 点击事件处理 canvas.addEventListener('click', function(e){ const x = e.clientX; const y = e.clientY; // 获取点击位置的像素数据 const pixel = ctx.getImageData(x, y, 1, 1).data; const r = pixel[0], g = pixel[1], b = pixel[2]; // RGB转十六进制 const hex = '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase(); // 展示结果 alert('选取的颜色:' + hex); // 清理临时元素 body.removeChild(canvas); body.removeChild(overlay); }); })();
核心特性说明
- 兼容Chrome、Firefox、Safari等所有主流浏览器
- 通过canvas生成页面像素快照,支持用户点击任意位置取色
- 自动将RGB值转换为标准十六进制颜色格式,通过alert展示
- 取色完成后自动清理临时元素,不残留页面干扰
使用步骤
- 浏览器中新建书签
- 将书签的URL替换为上述代码
- 点击书签激活取色器,点击页面任意位置即可获取对应颜色的十六进制值
内容的提问来源于stack exchange,提问作者Polar
相关产品推荐
相关产品推荐

