HTML5利用canvas,把多张图合并成一张图片

需求分析,根据当前网页中的几张图片,在手机上长按,保存图片到相册或者发送给好友。

drawCanvas(){
    var self = this;
    var imgsrcArray = [
        require('@/page/agent/agentexpand/img/bg.jpg'),
        'data:image/jpeg;base64,'+this.codeUrl
    ];
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = 750;
    canvas.height = 1333;
    var imglen = imgsrcArray.length;
    var drawimg = (function f(n){
        if(n < imglen){
            var img = new Image();
            img.crossOrigin = 'Anonymous'; //解决跨域问题
            img.onload = function(){
                //ctx.save();
                if(n == 0){
                    ctx.drawImage(img,0,0,750,1333);
                }else{
                    ctx.drawImage(img,466,574,210,210);
                }
                f(n+1);
            }
            
            img.src = imgsrcArray[n];
        }else{
            self.downloadUrl = canvas.toDataURL("image/jpeg");
            self.downloadUrl = self.downloadUrl.replace("data:image/jpeg;base64,", "");
        }
    })(0);
}

调用方式:

<img :src="'data:image/jpeg;base64,' + downloadUrl"/>

注:上面的调用是使用的vue语法。

可参考地址:

posted @ 2018-03-08 15:32  风雨后见彩虹  阅读(17644)  评论(2编辑  收藏  举报