<div class="image-container">
<img ref="myImg" style="width: 100%;display: none;" src="../assets/logo.png" alt="My Image" @load="getMainColor()"/>
</div>
const myImg = ref(null); // 创建一个引用变量
const getMainColor=()=> {
const img = myImg.value; // 通过ref属性获取到图片元素
const canvas = document.createElement('canvas'); // 创建画布对象
const context = canvas.getContext('2d'); // 获取上下文
canvas.width = img.naturalWidth || img.clientWidth; // 设置画布大小为图片原始宽度或者客户区域宽度(如果未定义)
canvas.height = img.naturalHeight || img.clientHeight; // 设置画布高度为图片原始高度或者客户区域高度(如果未定义)
context.drawImage(img, 0, 0); // 将图片绘制到画布上
img.crossOrigin = ''//防止跨域报错不能使用,但依然会报错
const imageData = context.getImageData(0, 0, canvas.width, canvas.height).data; // 获取图像数据
let rTotal = 0;
let gTotal = 0;
let bTotal = 0;
for (let i = 0; i < imageData.length; i += 4) {
rTotal += imageData[i];
gTotal += imageData[i + 1];
bTotal += imageData[i + 2];
}
const totalPixels = imageData.length / 4;
const avgR = Math.round(rTotal / totalPixels);
const avgG = Math.round(gTotal / totalPixels);
const avgB = Math.round(bTotal / totalPixels);
console.log(`Average RGB color of the image is (${avgR}, ${avgG}, ${avgB})`);
}
Vue3 获取图片主色(平均色)js
于 2024-03-01 09:55:24 首次发布