jQuery怎么让body根据图片颜色,来变化body的背景色
1个回答
展开全部
你可以通过canvas先计算出图片的主色调,然后给body设置这个颜色的背景
代码:
const img = new Image();
img.src = 'xxx.png'
img.onload = function() {
const { width, height } = img;
const scaleRect = width * height;
let sum_r = 0, sum_g = 0, sum_b = 0;
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0);
const imgData = ctx.getImageData(0,0, canvas.width, canvas.height);
for (let i=0; i<imgData.data.length; i+=4) {
const r = imgData.data[i];
const g = imgData.data[i+1];
const b = imgData.data[i+2];
sum_r += r;
sum_g += g;
sum_b += b;
}
const avg_r = Math.round(sum_r / scaleRect);
const avg_g = Math.round(sum_g / scaleRect);
const avg_b = Math.round(sum_b / scaleRect); // 主色调
const mainColor = `rgb(${avg_r}, ${avg_g}, ${avg_b})`;
}
代码:
const img = new Image();
img.src = 'xxx.png'
img.onload = function() {
const { width, height } = img;
const scaleRect = width * height;
let sum_r = 0, sum_g = 0, sum_b = 0;
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0);
const imgData = ctx.getImageData(0,0, canvas.width, canvas.height);
for (let i=0; i<imgData.data.length; i+=4) {
const r = imgData.data[i];
const g = imgData.data[i+1];
const b = imgData.data[i+2];
sum_r += r;
sum_g += g;
sum_b += b;
}
const avg_r = Math.round(sum_r / scaleRect);
const avg_g = Math.round(sum_g / scaleRect);
const avg_b = Math.round(sum_b / scaleRect); // 主色调
const mainColor = `rgb(${avg_r}, ${avg_g}, ${avg_b})`;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询