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>
相关推荐
负责的蛋挞15 分钟前
异步HttpModule的实现方式
java·服务器·前端
丹宇码农3 小时前
把 HLS 字幕玩出花:zwPlayer 如何让 M3U8 视频支持全文搜索、翻译与码率自适应
前端·javascript·音视频·hls·视频播放器
2501_943782353 小时前
【共创季稿事节】猜数字游戏:二分法思维与交互式反馈
前端·游戏·microsoft·harmonyos·鸿蒙·鸿蒙系统
GV191rLvq3 小时前
基于Socket实现的最简单的Web服务器【ASP.NET原理分析】
服务器·前端·asp.net
吠品3 小时前
LangChain 里 tool_call_id 为空?一次 MCP 工具集成的排查记录
前端
微信开发api-视频号协议4 小时前
企业微信二次开发中的文件系统设计:媒体资源、临时文件与业务附件
前端·微信·企业微信·媒体·ipad·微信开放平台
柒和远方4 小时前
Phase 7.4 学习博客:为什么多 API 项目需要 Swagger / OpenAPI
前端·后端·架构
张龙6874 小时前
拼多多开放平台对接踩坑实录:从 CLIENT_ID 配置到 MD5 签名算法的完整填坑指南
前端
GuWenyue4 小时前
提示词彻底过时?一套上下文工程方案,3步让LLM落地生产,代码直接复用
前端·javascript·人工智能