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>
相关推荐
Lkstar20 分钟前
Vue keep-alive 原理全解:LRU 缓存策略、源码级理解
前端·vue.js·面试
会联营的陆逊21 分钟前
html2canvas 1.4.1 在 iOS Safari 中生成图片卡住的问题排查与修复
前端
ZC跨境爬虫43 分钟前
跟着 MDN 学CSS day_13 :(深入理解CSS中的元素尺寸调整)
前端·javascript·css·ui·html·tensorflow
threelab1 小时前
Three.js 加载 3D Tiles 瓦片数据 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
百度地图开放平台1 小时前
我用百度地图 Skills 体系重构了物流调度系统,节省了 90% 的人力
前端·github
JavaAgent架构师1 小时前
前端AI工程化(九):AI Agent平台前端架构设计
前端·人工智能
_洋2 小时前
Three.js加载 .obj文件 和 .gltf文件
开发语言·javascript·ecmascript
梦想CAD控件2 小时前
网页端对DWG图纸进行预览与批注(CAD轻量化)
java·前端·javascript
JustNow_Man3 小时前
【opencode】安装使用daytona沙箱插件
android·java·javascript
不吃土豆的马铃薯3 小时前
Spdlog 进阶:日志基本控制、日志格式控制、异步记录器
linux·服务器·开发语言·前端·c++