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>
相关推荐
棉猴8 分钟前
Python海龟绘图之绘制文本
javascript·python·html·write·turtle·海龟绘图·输出文本
Codebee24 分钟前
Harness Engineering:AICode 的灵魂
前端·人工智能·前端框架
Highcharts.js41 分钟前
线形比赛积分增长或竞赛图|Highcharts企业图表代码示列
开发语言·前端·javascript·折线图·highcharts·竞赛图
hpysirius44 分钟前
在企业搭建一套完整的AI Agent系统
前端
追逐梦想永不停44 分钟前
记录一个好用的excel判断数字格式的公式
前端·chrome·excel
hpysirius1 小时前
从零构建 Web 端视频剪辑器:技术实践与思考
前端
让学习成为一种生活方式1 小时前
大肠杆菌合成扑热息痛--对乙酰氨基酚--文献精读227
开发语言·前端·javascript
李白的天不白1 小时前
请求不到百度网址的原因
前端
多秋浮沉度华年1 小时前
electron 初始使用记录
javascript·arcgis·electron
Gary Studio1 小时前
Selinux编写
linux·服务器·前端