Vue3实现一个拾色器功能

<template>
  <div class="color">
    <button v-if="hasEyeDrop" @click="nativePick">点击取色</button>
    <input v-else type="color" @input="nativePick" v-model="selectedColor" />
    <p>所选颜色: {{ selectedColor }}</p>
    <p>RGB颜色: {{ rgbColor }}</p>
  </div>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue';

const hasEyeDrop: boolean = 'EyeDropper' in window;
const selectedColor = ref<string>('#ffffff'); // 使用ref来创建响应式数据
let result: Record<string, any> = {}; // 用于存储选择的颜色信息

const rgbColor = computed(() => {
  const hex = selectedColor.value.replace('#', '');
  const r = parseInt(hex.substring(0, 2), 16);
  const g = parseInt(hex.substring(2, 4), 16);
  const b = parseInt(hex.substring(4, 6), 16);
  return `rgb(${r}, ${g}, ${b})`;
});

async function nativePick(e: Event): Promise<void> {
  const val = e ? (e.target as HTMLInputElement).value : null;
  if (val) {
    selectedColor.value = val; // 更新选中的颜色
    console.log('获得颜色: ' + val);
  } else {
    const eyeDropper = new (window as any).EyeDropper(); // 初始化一个EyeDropper对象
    console.log('按Esc可退出');
    try {
      const colorResult = await eyeDropper.open(); // 开始拾取颜色
      selectedColor.value = colorResult.sRGBHex; // 更新选中的颜色
      result = colorResult; // 存储颜色信息
      console.log('获得颜色: ' + colorResult.sRGBHex);

      // 使用result变量
      console.log(result);
    } catch (e) {
      console.log('用户取消了取色');
    }
  }
}
</script>


<!-- // import { ref } from 'vue';
// const hasEyeDrop: boolean = 'EyeDropper' in window;
// const selectedColor = ref<string>('#ffffff'); // 使用ref来创建响应式数据
// let result: Record<string, any> = {}; // 用于存储选择的颜色信息

// async function nativePick(e: Event): Promise<void> {
//   const val = e ? (e.target as HTMLInputElement).value : null;
//   if (val) {
//     selectedColor.value = val; // 更新选中的颜色
//     console.log('获得颜色: ' + val);
//   } else {
//     const eyeDropper = new (window as any).EyeDropper(); // 初始化一个EyeDropper对象
//     console.log('按Esc可退出');
//     try {
//       const colorResult = await eyeDropper.open(); // 开始拾取颜色
//       selectedColor.value = colorResult.sRGBHex; // 更新选中的颜色
//       result = colorResult; // 存储颜色信息
//       console.log('获得颜色: ' + colorResult.sRGBHex);
      
//       // 使用result变量
//       console.log(result);
//     } catch (e) {
//       console.log('用户取消了取色');
//     }
//   }
// }
<style>
.color {
  width: 100%;
  height: 100%;
  background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);
}
</style> -->

效果图
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值