html根据图片变换背景色

html根据图片变换背景色

javascript 复制代码
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <style>
        .item {
            width: 50%;
            height: 80vh;
            margin: 0 auto;
            border: 1px solid red;
        }
    </style>
</head>

<body>
    <img src="./img/1.png" alt="" style="width: 200px;height: 200px;border: 1px solid red;">
    <script>
        // Load the image
        const img = new Image();
        img.src = './img/1.png';

        // Wait for the image to load
        img.onload = function () {
            // Create a canvas element
            const canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;

            // Draw the image onto the canvas
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);

            // Get the dominant color of the image
            const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
            const colors = {};
            for (let i = 0; i < imageData.data.length; i += 4) {
                const r = imageData.data[i];
                const g = imageData.data[i + 1];
                const b = imageData.data[i + 2];
                const color = `${r},${g},${b}`;
                if (colors[color]) {
                    colors[color]++;
                } else {
                    colors[color] = 1;
                }
            }
            const dominantColor = Object.keys(colors).reduce((a, b) => colors[a] > colors[b] ? a : b);

            // Set the background color of the webpage to the dominant color
            document.body.style.backgroundColor = `rgb(${dominantColor})`;
        };
    </script>

</body>

</html>
相关推荐
甲维斯13 分钟前
GLM5.2超过Opus4.8Think,全球第二了!
前端·人工智能·ai编程
by————组态16 分钟前
Ricon组态系统 - 新一代Web可视化组态平台
前端·后端·物联网·架构·组态·组态软件
JieE21216 分钟前
手把手带你用纯 CSS 实现一个 3D 旋转魔方,这些前端基础你能打几分?
前端·css·html
lichenyang45329 分钟前
鸿蒙 Web 容器(二):H5 和 ArkTS 说话前,先定一份「协议」
前端
JYeontu32 分钟前
开箱流水加载动画
前端·javascript·css
RANxy33 分钟前
AntV 入门系列:G6 图可视化实战
前端
尽欢i34 分钟前
Vue3 customRef 封神教程:防抖、本地存储、自动埋点一套搞定,模板干干净净
前端·javascript·vue.js
VOLUN37 分钟前
TypeScript封装通用RESTful BaseAPI,后台接口代码精简80%
前端·javascript
胡永双38 分钟前
Hexo + GitHub Pages搭建个人Blog教程(三)
前端