本文主要是介绍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> -->
效果图

这篇关于Vue3实现一个拾色器功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!