html展示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
      <img class="compoundImg" src="" alt="" style="max-width: 95%;display: block;margin: auto;">
</body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</html>

js代码

<script>
    (function (global, factory) {
        typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
            typeof define === 'function' && define.amd ? define(factory) :
                (global.mergeImages = factory());
    }(this, (function () {
        'use strict';
        // Defaults
        var defaultOptions = {
            format: 'image/png',
            quality: 0.92,
            width: undefined,
            height: undefined,
            Canvas: undefined,
            crossOrigin: undefined,

        };
        // Return Promise
        var mergeImages = function (sources, options) {
            if (sources === void 0) sources = [];
            if (options === void 0) options = {};

            return new Promise(function (resolve) {
                options = Object.assign({}, defaultOptions, options);

                // Setup browser/Node.js specific variables
                var canvas = options.Canvas ? new options.Canvas() : window.document.createElement('canvas');
                var Image = options.Image || window.Image;

                // Load sources
                var images = sources.map(function (source) {
                    return new Promise(function (resolve, reject) {
                        // Convert sources to objects
                        if (source.constructor.name !== 'Object') {
                            source = {src: source};
                        }

                        // Resolve source and img when loaded
                        var img = new Image();
                        img.crossOrigin = options.crossOrigin;
                        img.onerror = function () {
                            return reject(new Error('Couldn\'t load image'));
                        };
                        img.onload = function () {
                            return resolve(Object.assign({}, source, {img: img}));
                        };
                        img.src = source.src;
                    });
                });

                // Get canvas context
                var ctx = canvas.getContext('2d');

                // When sources have loaded
                resolve(Promise.all(images)
                    .then(function (images) {
                        // Set canvas dimensions
                        var getSize = function (dim) {
                            return options[dim] || Math.max.apply(Math, images.map(function (image) {
                                return image.img[dim];
                            }));
                        };

                        canvas.width = getSize('width');
                        canvas.height = getSize('height');

                        let row = options.row //每行展示几个
                        let astrictNum = Math.ceil(images.length / row) //几行
                        //获取最终生成图片的最高值,取出最大的两值,并设置canvas.height
                        let lastWidth = 0
                        let lastHeight = 0
                        let lastHeight_d = 0
                        let canvasWidthAndHeight = []
                        images.forEach(function (image, i) {
                            canvasWidthAndHeight.push({
                                w: image.img.naturalWidth,
                                h: image.img.naturalHeight
                            })
                        })
                        //console.log(canvasWidthAndHeight);
                        let sort = (arr, key) => {
                            //根据对象某个属性排序
                            let len = arr.length
                            for (let i = 0; i < len; i++) {
                                for (let j = 0; j < len - 1 - i; j++) {
                                    //进行len次数遍历
                                    if (arr[j][key] < arr[j + 1][key]) { //相邻元素两两对比
                                        //元素交换
                                        let temp = arr[j + 1]
                                        arr[j + 1] = arr[j]
                                        arr[j] = temp;
                                    }
                                }
                            }
                            return arr
                        }
                        let lastWidth_fn = () => {
                            let w = 0
                            let arr = sort(canvasWidthAndHeight, 'w')
                            for (let a = 0; a < astrictNum + 1; a++) {
                                w += arr[a].w
                            }
                            return w
                        }
                        let lastHeight_fn = () => {
                            let h = 0
                            let arr = sort(canvasWidthAndHeight, 'h')
                            for (let a = 0; a < astrictNum; a++) {
                                h += arr[a].h
                            }
                            for (let a = 0; a < astrictNum + 1; a++) {
                                lastHeight_d += arr[a].h

                            }
                            return h
                        }
                        lastWidth = lastWidth_fn()
                        lastHeight = lastHeight_fn()


                        canvas.width = lastWidth + (options.spaceBetween * row)
                        canvas.height = lastHeight + (options.spaceBetween * row)
                        //console.log(canvas.width, canvas.height);
                        // Draw images to canvas
                        images.forEach(function (image, i) {
                            //console.log(image);
                            ctx.globalAlpha = image.opacity ? image.opacity : 1;


                            let p_x = [], p_y = [];
                            for (let u = 0; u < astrictNum; u++) {
                                for (let j = 0; j < row; j++) {
                                    p_x.push(j)
                                }
                            }
                            for (let u = 0; u < astrictNum; u++) {
                                for (let j = 0; j < row; j++) {
                                    p_y.push(u)
                                }
                            }
                            let x, y;
                            x = p_x[i] * (lastWidth / row) + options.spaceBetween * p_x[i]
                            y = p_y[i] * (lastHeight_d / row) + options.spaceBetween * p_y[i]
                            image.x = x
                            image.y = y
                            //console.log(`x=${image.x}`, `y=${image.y}`);

                            return ctx.drawImage(image.img, image.x || 0, image.y || 0, (lastWidth / row), (lastHeight_d / row));
                        });


                        if (options.Canvas && options.format === 'image/jpeg') {
                            // Resolve data URI for node-canvas jpeg async
                            return new Promise(function (resolve, reject) {
                                canvas.toDataURL(options.format, {
                                    quality: options.quality,
                                    progressive: false
                                }, function (err, jpeg) {
                                    if (err) {
                                        reject(err);
                                        return;
                                    }
                                    resolve(jpeg);
                                });
                            });
                        }

                        // Resolve all other data URIs sync
                        return canvas.toDataURL(options.format, options.quality);
                    }));
            });
        };

        return mergeImages;

    })));
    let compoundImg = () => {
        let ahref = 'http://www.images-test.com/images/1.jpg,http://www.images-test.com/images/2.jpg,http://www.images-test.com/images/home.png,http://www.images-test.com/images/home1.png,http://www.images-test.com/images/list.png,http://www.images-test.com/images/list1.png'
        let ahref_arr = ahref.split(',')
        let widthAndHeight = {
            row: 3,
            spaceBetween: 10, //边距
            crossOrigin: 'Anonymous'
        }
        mergeImages(ahref_arr, widthAndHeight).then(
            b64 => {
                document.querySelector('.compoundImg').src = b64
            }
        )
    }
    compoundImg()
</script>
Last modification:July 2, 2022
如果觉得我的文章对你有用,请随意赞赏