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>
相关推荐
Yoram4 分钟前
Vue3 响应性:跨上下文的传递、转换与作用域控制
前端·vue.js
掘金安东尼6 分钟前
开源小工具:掘金福利页「补签卡」按次数自动兑换(Chrome 扩展)
前端·开源
Mike_jia16 分钟前
Sirius Scan:开源漏洞扫描利器,重塑企业安全防护体系
前端
知兀23 分钟前
【前端】默认导出和命名导出区别
前端
XS03010630 分钟前
Servlet+JQuery实现数据库数据渲染到前端页面
前端·servlet·jquery
yqcoder36 分钟前
深入理解 JavaScript:什么是可迭代对象 (Iterable)?
开发语言·javascript·网络
van久1 小时前
Day27:菜单管理 + 动态路由(前端可直接用!)
前端·状态模式
恋猫de小郭1 小时前
DeepSeek V4 Flash 可以在 128GB 的 M3 Max 运行,还是 1M 上下文
前端·人工智能·ai编程
van久1 小时前
企业级后台管理系统(结合前 4 周全部内容)详细需求文档 + 前端模板适配
前端
Lsx_1 小时前
H5 嵌入微信 / 支付宝 / 抖音小程序 WebView:调用原生能力完整方案
前端·微信小程序·webview