项目中遇到个需求,要把带个人参数的二维码的分享图分享到微信,让两个用户绑定。
这是分享之前的样式,要用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();//开始下载
},