混合APP中實現合成帶參數二維碼的圖片並分享到微信

項目中遇到個需求,要把帶個人蔘數的二維碼的分享圖分享到微信,讓兩個用戶綁定。

這是分享之前的樣式,要用canvas把它做成一整張圖片,如果不是APP中是在微信會H5中可以進入頁面就製作,覆蓋在原圖上讓用戶長按圖片下載。
在這裏插入圖片描述
在這裏插入圖片描述
分享之前用戶可以自由搭配分享樣式,這是分享在微信中的樣子。

首先可以去BootCDN下載html2canvas引入項目中。
直接上代碼

//畫圖
    	huatu:function(){
    		    plus.nativeUI.showWaiting('製作中...');
				  var that=this;
	      		var shareContent = $(".img_imagebox")[0]; //$(".img_imagebox")中包含樣式圖片與二維碼
			    var width = shareContent.offsetWidth; 
			    var height = shareContent.offsetHeight;
			    var canvas = document.createElement("canvas"); 
			    var scale = 2; 
			    canvas.width = width * scale; 
			    canvas.height = height * scale; 
			    canvas.getContext("2d").scale(scale, scale); 
			    var rect = shareContent.getBoundingClientRect();
			    canvas.getContext("2d").translate(-rect.left,-rect.top);
			    var opts = {
			        scale: scale, 
			        canvas: canvas, 
			        width: width, 
			        height: height,
			        useCORS:true
			    };
			    html2canvas($(".img_imagebox")[0], opts).then(function (canvas) {
			        var dataURL =canvas.toDataURL("image/png").split(",")[1];//生成base64的圖片	
			                //將圖片傳到後端服務器換取網絡地址進行保存				
						    that.$http.post(that.GLOBAL.host+'/wx/shareUpload', {
								imgStr:dataURL,
								userNumber:sessionStorage.getItem("kbj_userNumber")
							})
							.then(function (res) {
									if(res.data.code==0){																				that.saveimg(that.GLOBAL.yum+"/uploadpath/"+res.data.fileName);
									}else{
										plus.nativeUI.closeWaiting();
										alert("獲取數據失敗")
									}
							})
							.catch(function (error) {
								plus.nativeUI.closeWaiting();
								alert("請求數據失敗")
							});
								
			    });
        },
//保存圖片到本地
		saveimg:function (picurl) {
			var that=this;
			     plus.nativeUI.showWaiting('下載中...');				
				var dtask = plus.downloader.createDownload(picurl, {}, function ( d, status ) {
					// 下載完成
					if ( status == 200 ) { 
						plus.gallery.save(d.filename,function() {//保存到相冊方法
						plus.nativeUI.closeWaiting();
						mui.toast('已保存到手機相冊');
						self.location='weixin://'; //保存成功跳轉到微信
					}, function() {
						plus.nativeUI.closeWaiting();
						mui.toast('保存失敗,請重試!');
					});
					} else {
						plus.nativeUI.closeWaiting();
						console.log( "Download failed: " + status ); 
						mui.toast("下載失敗");
					}
				});
				dtask.start();//開始下載
		},
    	
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章