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 分钟前
B2B 内容营销的工程化运营:从内容矩阵建模到 SEO/GEO 联动的完整体系
前端·线性代数·矩阵·网站建设·北京网站建设公司
2501_940041745 分钟前
全栈开发提速指南:可以直接用的项目生成提示词
前端·prompt
BomanGe27 分钟前
NSK直线导轨LH55EL与NH55EM替代指南
前端·javascript·数据库·经验分享·规格说明书
云水一下7 分钟前
Vue.js从零到精通系列(四):前端路由与Vue Router——打造多页单页应用
前端·javascript·vue.js
糯米导航9 分钟前
浏览器解析HTML头部的底层逻辑:从字节流到渲染树的关键一步
前端·html
风骏时光牛马13 分钟前
C++开发常见问题与解决方案汇总
前端
zhedream15 分钟前
Vue 3 Teleport 报错实录:从 patch 时机到 `defer` 属性
前端·vue.js
雁北向15 分钟前
自定义指令 数值输入显示优化 巴飞特 测试
前端·vue.js
研☆香17 分钟前
jQuery补充知识点
前端·javascript·jquery
先吃饱再说19 分钟前
JavaScript栈和队列:从“冰柜里的雪糕”到“排队打饭”
javascript·数据结构