微信小程序 Canvas 签字 #95
发布时间:2023-06-27 17:00:19
最近迫于签字结果返回太慢,所以需要把旋转图片由原先后端处理改为前端处理,查阅文档,研究一番,发现小程序上旋转,主要是通过canvas的translate、rotate完成。
Canvas坐标系统,由上图可得,Canvas 2D 环境中坐标系统和 Web 的坐标系统是一致的,有以下几个特点:
坐标原点 (0,0) 在左上角
X坐标向右方增长
Y坐标向下方延伸
伪代码
wx.canvasToTempFilePath({ x: 0, y: 0, canvasId: 'myCanvas', success: (res) => { wx.getImageInfo({ src: res.tempFilePath, success: (imageRes) => { const height = imageRes.height; const width = imageRes.width; this.setState({ canvasHeight: width, canvasWidth: height }); const context2 = wx.createCanvasContext('myCanvas2', this.$scope); context2.translate(height / 2, width / 2); context2.rotate(270 * Math.PI / 180); context2.drawImage(imageRes.path, -width / 2, -height / 2, width, height); context2.draw(false, () => { this.getTempFilePath(); }); } }); }, fail: (error) => { console.error('canvasToTempFilePathfail', error); } }, this); // 获取图片url,安卓有性能问题,所以需要延迟 getTempFilePath(errorCount = 5) { setTimeout(() => { const { signInfo } = this.props; const { signers, signerNames } = this.state; wx.canvasToTempFilePath({ x: 0, y: 0, canvasId: 'myCanvas2', success: (res) => { const signPic = this.fileTobase64(res.tempFilePath); }, fail: (err) => { if(errorCount < 7) { this.getTempFilePath(++errorCount); } console.error('canvasToTempFilePathfail', err); } }, this); }, errorCount * 100); } fileTobase64 = path => { return 'data:image/jpeg;base64,' + Taro.getFileSystemManager().readFileSync(path, 'base64'); }; render() { return (