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>
相关推荐
feixing_fx34 分钟前
变量与声明:let、const、var 的选择边界
开发语言·前端·javascript·前端框架
程序员大阳1 小时前
副队长Vue3教程(8)--列表渲染 v-for
javascript·vue3·v-for·列表渲染
JavaGuide3 小时前
Cloudflare 开源的这套神级安全审计 Skill 太好用了!
前端·后端
孟健4 小时前
用 unslop 拯救 AI 生成网页的塑料感,7 分钟重构落地实测
前端·人工智能·ai编程
feixing_fx4 小时前
JavaScript 是什么:从浏览器脚本到通用编程语言
开发语言·前端·javascript·前端框架·ecmascript
丘山望岳4 小时前
【开发工具】 cluade code常用快捷键
前端
小巫编程室5 小时前
我造了一个 Java 能力包:让 AI 直接调用你的业务代码
java·前端·后端
小y的笔记5 小时前
JavaScript URL 状态同步
前端·javascript
十有八七5 小时前
手搓 Agent(五):学会翻书——RAG,先查资料再回答
前端·人工智能·后端
Swot5 小时前
产品 RAG 知识库与 AI 顾问 设计与实现
前端·后端