js 也可做屏幕颜色拾取器了

最近在看到一些文章,出了一些新的api接口,可以提供给js做整个电脑屏幕颜色的拾取。差了下兼容性不是很好,但是该版本的浏览器是可以正常使用的。 这样对一些设计类的网站或者是需要到屏幕颜色拾取功能的也可以做!

主要是用到EyeDropper这个api参考

EyeDropper - Web APIs | MDN (mozilla.org)

代码如下:

<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width initial-scale=1.0 maximum-scale=1.0 user-scalable=0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>拾取颜色</title>
<style>
body,html{ margin:0;padding:0;font:12px/16px Verdana,Helvetica,Arial,sans-serif;width: 100%;height: 100%}
#container{
  height: 100%
  padding: 10px;
}
.color {
  display: block;
  height: 30px;
  width: 40px;
  border: 1px solid #ccc;
}
</style>

</head>
<body >
<div id="container">
  <span class="color"></span>
  <button>拾取</button>
</div>
<script language="javascript">
  document.querySelector('button').onclick = function () {
    const eyeDropper = new EyeDropper();
    eyeDropper.open().then(res => {
      document.querySelector('.color').style.background = res.sRGBHex;
    }).catch(err=>{
      console.log('用户取消拾取');
    });
  };
</script>
</body>
</html>

运行结果如下: 

猜你喜欢

转载自blog.csdn.net/CodingNoob/article/details/130635971