1.首先绘制canvas图片
<canvas id="myCanvas" width="100" height="100" style="border:1px solid #d3d3d3;border-radius:50%"> 您的浏览器不支持 HTML5 canvas 标签。 </canvas>
这里canvas绘图就不是本文章讲解的内容,我们简单的在画布上写两个字:
var canvas = document.getElementById("myCanvas"); var ctx = this.c.getContext("2d"); ctx.textAlign = ‘left‘; ctx.textBaseline = ‘top‘; ctx.font = ‘bold 16px arial‘; ctx.fillStyle = ‘red‘; ctx.fillText(‘World‘, 40,40);
效果如下
2.将图片转成二进制利用formdata上传
let src = canvas.toDataURL("image/png")//这里转成的是base64的地址,直接用到img标签的src是可以显示图片的 var fd = new FormData(); function dataURItoBlob(dataURI) {//图片转成Buffer var byteString = atob(dataURI.split(‘,‘)[1]); var mimeString = dataURI.split(‘,‘)[0].split(‘:‘)[1].split(‘;‘)[0]; var ab = new ArrayBuffer(byteString.length); var ia = new Uint8Array(ab); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return new Blob([ab], {type: mimeString}); } var blob = dataURItoBlob(src); fd.append(‘source_from‘,‘webpage_upload‘)//在formdata加入需要的参数 fd.append(‘file‘,blob)
/*以下是ng4的封装上传代码*/ var service = ()=>{ return this.repositoryService.uplodimage(fd) } var callback = (re)=>{ if(re[‘success‘]){ console.log(re) this.form.image_cover_contents = re.data.file_info.file_path; } } this.core.doServiceAndCallback(‘上传图片‘,service,callback)