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>
相关推荐
牧艺1 分钟前
cos-design v3.0:从 15 个 Demo 到 49 个组件的视觉特效库
前端·视觉设计
lichenyang4533 分钟前
ASCF 架构升级总览:WebRuntimePage 为什么要变薄
前端
道友可好4 分钟前
从今天开始:你的第一个 Harness Engineering 实践
前端·人工智能·后端
Linsk6 分钟前
组件 = 模板 + 业务逻辑
java·前端·vue.js
二月龙37 分钟前
移动端 H5 页面开发:响应式适配 + 低版本兼容实战指南
前端
小强198840 分钟前
HTML5 新表单全解:日期、手机号、颜色选择器
前端
妙码生花42 分钟前
从 PHP 到 AI + Golang,程序员自救转型手记(二):目录结构、初始化 GIT、设计并开发配置系统
前端·后端·go
鱼人43 分钟前
HTML5 本地存储终极指南
前端
超绝大帅哥1 小时前
React的Fiber是什么? Vue为什么不需要Fiber ?
前端
yingyima1 小时前
正则表达式分组与捕获:凌晨3点服务器报警的解决方案
前端