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>
相关推荐
小流苏生5 分钟前
工作十年了,慢慢学习敬畏死亡
前端·程序员·ai编程
xiaoxue..7 分钟前
react:浅聊 vdom 与 diff 算法
前端·javascript·react.js·面试
恋猫de小郭8 分钟前
Flutter 3.41.7 ,小版本但 iOS 大修复,看完只想说:这是人能写出来的 bug ?
android·前端·flutter
止语Lab11 分钟前
记忆溢出:当你的 Agent 记得太多时会发生什么
前端·javascript·vue.js
天天向上102412 分钟前
vue openlayers地图加载大量点位时优化
前端·javascript·vue.js
devil-J23 分钟前
vue3+three.js中国3D地图
开发语言·javascript·3d
菩提小狗39 分钟前
第42天:WEB攻防-PHP应用&MYSQL架构&SQL注入&跨库查询&文件读写_笔记|小迪安全2023-2024|web安全|渗透测试|
前端·安全·php
liuyouzhang4 小时前
将基于Archery的web数据库审计查询平台封装为jdbc接口的可行性研究(基于AI)
前端·数据库
码事漫谈9 小时前
大模型输出的“隐性结构塌缩”问题及对策
前端·后端
这儿有一堆花10 小时前
前端三件套真的落后了吗?揭开现代 Web 开发的底层逻辑
前端·javascript·css·html5