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>
相关推荐
_大龄12 分钟前
前端解析excel
前端·excel
1***s63215 分钟前
Vue图像处理开发
javascript·vue.js·ecmascript
槁***耿32 分钟前
JavaScript在Node.js中的事件发射器
开发语言·javascript·node.js
一叶茶34 分钟前
移动端平板打开的三种模式。
前端·javascript
前端大卫36 分钟前
一文搞懂 Webpack 分包:async、initial 与 all 的区别【附源码】
前端
U***498340 分钟前
JavaScript在Node.js中的Strapi
开发语言·javascript·node.js
Want5951 小时前
HTML音乐圣诞树
前端·html
老前端的功夫1 小时前
前端浏览器缓存深度解析:从网络请求到极致性能优化
前端·javascript·网络·缓存·性能优化
Running_slave2 小时前
你应该了解的TCP滑窗
前端·网络协议·tcp/ip
程序员小寒2 小时前
前端高频面试题之CSS篇(一)
前端·css·面试·css3