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>
相关推荐
墨鱼鱼2 分钟前
【征文计划】Rokid JSAR 实践指南:打造沉浸式 "声动空间盒" 交互体验
前端
渣哥2 分钟前
多环境配置利器:@Profile 在 Spring 项目中的实战价值
javascript·后端·面试
携欢5 分钟前
Portswigger靶场之Exploiting a mass assignment vulnerability通关秘籍
前端·安全
什么芋泥香蕉33013 分钟前
比 Manus 还好用?这款国产 AI,让 Python 小白也能玩转编程
前端·后端
为java加瓦14 分钟前
前端学AI:如何写好提示词(prompt)
前端·人工智能·prompt
U.2 SSD20 分钟前
Echart仪表盘示例
javascript·echarts
qq_18417767722 分钟前
前端自动部署项目到服务器
服务器·前端·javascript
非凡ghost23 分钟前
猫眼浏览器(Chrome内核增强版浏览器)官方便携版
前端·网络·chrome·windows·软件需求
Never_Satisfied29 分钟前
在JavaScript / HTML / Node.js中,post方式的Content-Type属性的text的三种编码
javascript·node.js·html
C2X37 分钟前
Vue3.0 学习总结
前端