微信小程序 base64图片在canvas上画图

上代码

wxml

<canvas canvas-id="myCanvas" style="width:400px;height:400px;"></canvas>

js

const ctx = wx.createCanvasContext('myCanvas'), //canvas
      fsm = wx.getFileSystemManager(),  //文件管理器
      FILE_BASE_NAME = 'tmp_base64src', //文件名
      format = 'png', //文件后缀
      base64Str = ('iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA3ZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDY3IDc5LjE1Nzc0NywgMjAxNS8wMy8zMC0yMzo0MDo0MiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDpiZDM3ZmYwZi0wZDgxLWRkNDMtYTBjOC05YzU1OWVmMmUyNmYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6QjJGNUNCMDIwMjc2MTFFOUIxNDFENzI5QTVGOTQ3NTAiIHhtcE1NOkluc3RhbmNlSUQ9Inh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BTP01N2oEegw/W4WqD92EK+WiTwx9KhjzynGmmzbFGnjlPvxugfUAY3dNCoLYTyNV46upZ9dcivYzbqz9qjnFeMhP8SjGwMQLGnbVWjlFLa7QfoZBbgBro8BzSTw47a+6a6dJFmVYEwFKhWTYPhrziG08WwyRC1WbSp8yviwk1aKa/8Dfj0HPDWvRv92De3sEVT8vZLwu2azdTAQpdCSsTaA2yOWR1zQ70RchfRb3ZsixgZxvP5SDghWH8Z27pL+EQfo3O9TTxATHu0Emgp6lnp1y/ypzhvaTR4opqlDU1ipr0mQQNebCkeZ8atAIlpQeQdF5woZy+sme4gQFhHTUqfosuzdUTPm8FBRwWDTrhq1fPyJJLftolCRi7ScHBb/D234y6kZYgQXF1WIHafZ9pdjBNb1RQ51Jz3HOKvsvxY+0pRXO6yn77SczQZC7BYf34XDReCEtY+0Z7AWi2Ln7FfgEY7lcJbIofB9MN23Smc/ixn+3GgQbBDfo9U+AAQAR3QEE8abLPQAAAABJRU5ErkJggg==') //base64字符串
    buffer = wx.base64ToArrayBuffer(base64Str), //base 转二进制
    filePath = `${wx.env.USER_DATA_PATH}/www.${format}`; //文件名

    fsm.writeFile({ //写文件
      filePath,
      data: buffer,
      encoding: 'binary',
      success(res) {
wx.getImageInfo({ //读取图片 src: filePath, success:
function(res) { console.log({ res }) ctx.drawImage(res.path, 0, 0, 150, 100) //画图 ctx.draw() }, error(res) { console.log({ res }) } }) } })

注意:base字符串没有头信息

posted @ 2019-03-29 16:01  两面一汤  阅读(1184)  评论(1编辑  收藏  举报