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>
相关推荐
Go 言 Go 语14 分钟前
Claude Code 核心加载机制详解
服务器·前端·数据库
朝阳3914 分钟前
CSS【详解】给子元素添加间距的最佳实践(含space 和 gap 的区别图解和面试的标准答案)
前端·css
s65166549616 分钟前
Makefile语法学习
java·linux·前端
悟空爬虫-彪哥24 分钟前
Stich接入Codex教程
java·前端·数据库
深海鱼在掘金24 分钟前
Next.js从入门到实战保姆级教程(第十五章):部署运维与 CI/CD
前端·ci/cd·next.js
Mr.mjw25 分钟前
vue中封装一个进度条组件,无需引入,纯css
javascript·css·vue.js
veminhe27 分钟前
Java后端、PC前端学习备忘
前端
深海鱼在掘金28 分钟前
Next.js从入门到实战保姆级教程(第十七章):综合实战项目(下)——前端页面、性能优化与部署
前端·ci/cd·next.js
深海鱼在掘金28 分钟前
Next.js从入门到实战保姆级教程(第十六章):实战项目(上)——全栈博客系统架构与核心功能
前端·数据库·next.js
茅盾体39 分钟前
Electron图标相关
java·前端·electron