canvas图片拼接(横向)

2019-04-24  本文已影响0人  王昌浩xi

canvas图片拼接(横向)

之前的工作中遇到的拼接图片问题,于是写了这个图片拼接。大家一起看看吧!

毫无疑问,这次我们的技术栈是H5的canvas,代码有点长。大家耐心查看(建议PC)!


HTML部分

   // 样板图片
    <div align="center" class="img_photo">
        <img src="http://pre-bj-trace-image.oss-cn-beijing.aliyuncs.com/full/20180919/de963ab401235d894aaf100eb8f12bbd.jpg" width="250px" height="562px">
        <img src="http://pre-bj-trace-image.oss-cn-beijing.aliyuncs.com/full/20180919/87ee27637fc789008ea782ce964be44e.jpg" width="250px" height="562px">
        <img src="http://pre-bj-trace-image.oss-cn-beijing.aliyuncs.com/full/20180919/f0d50c02c0f2b3f55846aa0183ce675e.jpg" width="250px" height="562px">
        <img src="http://pre-bj-trace-image.oss-cn-beijing.aliyuncs.com/full/20180919/ad81e8d020345e7b0a1715e7a680fddb.jpg" width="250px" height="562px">
    </div>
    <button align="center" id='save-img'>合成</button>
    // 展示合成图
    <div id="image-container"></div>

javaScript部分

    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
        // 拼出来的图片的宽度
        const height = 300
        // 拼出来的图片的质量,0-1之间,越大质量越好
        const encoderOptions = 1

        const uploadInput = document.getElementById('save-img');
        const imageDiv = document.getElementById('image-container');

        uploadInput.addEventListener('click', event => {
            const data1= new Array();
            for(let i=0;i<$('.img_photo img').length;i++){
                data1[i]=$('.img_photo img').eq(i).attr('src');
            }
            filesToInstances(data1, instances => {
                console.log(instances)
                drawImages(instances, finalImageUrl => {
                    console.log(instances)
                    imageDiv.innerHTML = `<div><a download href=${finalImageUrl}>点击下载</a><br><img src=${finalImageUrl}></div>`
                })
            })
        })
        // 根据图片文件拿到图片实例
        const filesToInstances = (files, callback) => {
            const length = files.length
            console.log(files)
            let instances = []
            let finished = 0

            files.forEach((file, index) => {
                console.log(file)
                getBase64(file).then(function(base64){
                    let img = base64
                    const image = new Image()
                    image.src = img
                    image.onload = () => {
                        // 图片实例化成功后存起来
                        instances[index] = image
                        finished ++
                        if (finished === length) {
                            callback(instances)
                        }
                    }
                },function(err){});
                // }
            })
        }
        // 拼图
        const drawImages = (images, callback) => {
            console.log(images)
            const canvas = document.createElement('canvas')
            canvas.height = height; // canvas 拼出来之后的高度,即为图片高度
            // 每张图片的宽度(这里写死了,建议动态)
            const widths = images.map(item => {console.log(item); return 250; });
            console.log(widths)
            // canvas 拼出来之后的总宽度(横向拼接)
            canvas.width = 1000;
            console.log(canvas.width)
            const context = canvas.getContext('2d')

            let x = 0

            images.forEach((item, index) => {
                const width = widths[index]
                context.drawImage(item, x, 0, width, height)
                x += width
            })
            callback(canvas.toDataURL('image/jpeg', encoderOptions))
        }
        // 图片转base64
        const getBase64 = (img) =>{
            const getBase64Image = (img,width,height) => {//width、height调用时传入具体像素值,控制大小 ,不传则默认图像大小
            let canvas = document.createElement("canvas");
            canvas.width = width ? width : img.width;
            canvas.height = height ? height : img.height;
    
            let ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            let dataURL = canvas.toDataURL();
            return dataURL;
            }
            let image = new Image();
            image.crossOrigin = '';
            image.src = img;
            let deferred=$.Deferred();
            if(img){
            image.onload = () => {
                deferred.resolve(getBase64Image(image));//将base64传给done上传处理
            }
            return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest']
            }
        }
    </script>
</body>

这种方法在本地测试是完全没问题,但是放到线上成图率的确有点低。总是timeout,望大家查看优化。

上一篇下一篇

猜你喜欢

热点阅读