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>
相关推荐
hulkie5 分钟前
从 AI 对话应用理解 SSE 流式传输:一项 "老技术" 的新生
前端·人工智能
dobym9 分钟前
里程碑五:Elpis框架npm包抽象封装并发布
前端
全栈老石12 分钟前
手写无限画布4 —— 从视觉图元到元数据对象
前端·javascript·canvas
牛奶12 分钟前
React 底层原理 & 新特性
前端·react.js·面试
parade岁月19 分钟前
Tailwind CSS v4 — 当框架猜不透你的心思
前端·css
小明91322 分钟前
基于Rokid CXR-M SDK的AI饮食健康助手开发实战
前端
一枚前端小姐姐23 分钟前
低代码平台表单设计系统技术分析(实战三)
前端·vue.js·低代码
牛奶23 分钟前
ts随笔:面向对象与高级类型
前端·面试·typescript
牛奶24 分钟前
React 基础理论 & API 使用
前端·react.js·面试
大漠_w3cpluscom27 分钟前
别再死记CSS属性了!真正能让你少走半年弯路的,是这套思维
前端