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>
相关推荐
nn_(nana)16 分钟前
修改文件权限--- chmod ,vi/vim,查看文件内容,yum-软件包管理器,systemctl管理系统服务
前端
汪汪队立大功12323 分钟前
JavaScript是怎么和html元素关联起来的?
开发语言·javascript·html
烛阴1 小时前
从零开始掌握C#核心:变量与数据类型
前端·c#
han_1 小时前
前端高频面试题之Vuex篇
前端·vue.js·面试
qq_415216252 小时前
vue3搭建项目yarn+vue3+webpack+less+element-plus
前端·webpack·less
天天向上10242 小时前
VueUse的使用
前端·vue.js·vscode
猪猪拆迁队3 小时前
前端图形引擎架构设计:双引擎架构设计
前端·后端·架构
宋辰月3 小时前
学习react第三天
前端·学习·react.js
bug总结3 小时前
更新原生小程序封装(新增缓存订阅)完美解决
前端·缓存·小程序
GISer_Jing3 小时前
Node.js 开发实战:从入门到精通
javascript·后端·node.js