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>
相关推荐
zheshiyangyang27 分钟前
前端面试基础知识整理【Day-7】
前端·面试·职场和发展
猫头虎33 分钟前
web开发常见问题解决方案大全:502/503 Bad Gateway/Connection reset/504 timed out/400 Bad Request/401 Unauthorized
运维·前端·nginx·http·https·gateway·openresty
qq_242188633236 分钟前
3389端口内网转发概述
前端·经验分享·html
Never_Satisfied1 小时前
在JavaScript / HTML中,数组查找第一个符合要求元素
开发语言·javascript·html
伊泽瑞尔1 小时前
2025年终总结
前端·程序员·ai编程
uhakadotcom2 小时前
Hono v4.12.0 发布!路由提速2倍+,JSON响应飞起来
前端·面试·github
少云清2 小时前
【UI自动化测试】10_web自动化测试 _frame切换、多窗口切换
前端·web自动化测试
HelloReader2 小时前
做 IM 客户端,选 Tauri 还是 Qt一篇把坑讲清楚的选型与架构指南
前端
HelloReader2 小时前
Tauri 2 创建项目全流程create-tauri-app 一键脚手架 + Tauri CLI 手动接入
前端·javascript·vue.js
Full Stack Developme2 小时前
语法树与自动化技术
运维·前端·自动化