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>
相关推荐
IT_陈寒5 分钟前
Redis的Set操作居然能把我的服务整挂了?
前端·人工智能·后端
计算机魔术师38 分钟前
Suno 发布 v6 音乐模型,推出 v6、v6-wild、v6-mini 三个版本
前端
whyweplay1 小时前
elpis : DSL动态组件学习
前端
用户921080262861 小时前
前端 Vue 专栏 06:异步更新机制、任务队列与 nextTick
前端
杨芋爽2 小时前
管理后台列表页为什么一直转圈?从一次 1+N 请求扇出聊聊前端性能优化
javascript
晴天162 小时前
Chrome DevTools 深度调试指南
前端·chrome·chrome devtools
林冠宏_指尖下的幽灵2 小时前
AI发展下的后编程时代思考
前端·人工智能·后端
_山海2 小时前
Bun入门指南
前端·javascript·后端
想睡懒觉2 小时前
我用 CSS 3D 做了个星空隧道 Loading,没有 Three.js
前端