canvas保存图片为空白?
发布于 5 年前 作者 phan 3802 次浏览 来自 问答

代码部分

   
  happyNow() {
    console.log(1)
    // 获取并设置画布的信息
    const canvasQuery = wx.createSelectorQuery()
    canvasQuery.select('#MyCanvas')
      .fields({
        nodetrue,
        sizetrue,
        recttrue
      })
      .exec(this.CanvasInit.bind(this))
      
  },
  CanvasInit(res) {
    console.log(res)
    const width = res[0].width
    const height = res[0].height

    const canvas = res[0].node
    const ctx = canvas.getContext('2d')

    const dpr = wx.getSystemInfoSync().pixelRatio
    canvas.width = width * dpr
    canvas.height = height * dpr
    ctx.scale(dpr, dpr)

    //画布背景颜色
    ctx.fillStyle = '#fff'
    ctx.fillRect(00, width, height)
    // 绘制图片
    const img = canvas.createImage()
    img.src = ImgPath
    img.onload = () => ctx.drawImage(img, 00this.widthImg, this.heightImg)

    // 绘制文字部分
    console.log(this.widthImg)
    ctx.fillStyle = "#000000"
    ctx.font = "normal 18px Arial"
    ctx.fillText(this.time, 18this.heightImg + 20)
    ctx.fillText(this.wea, 150this.heightImg + 20)
    this.canvasText(ctx)
    wx.canvasToTempFilePath({
      canvas: canvas,
      x:0,
      y:0,
      width:width,
      height:height,
      destWidth:width,
      destHeight:height,
      success:res=>{
        console.log(res.tempFilePath)//http://tmp/3ifoGRo7kGKW1cc162bcbe1b93b416a623f78e0d96d9.png 这个图片无法打开
        this.saveTempFilePath = res.tempFilePath
      },
      fail:err=>{
        console.log(err)
      }
    })
  },
  canvasText(ctx) {
    let num = parseInt(this.userText.length / 14)
    console.log(num)
    let aa = this.userText.length % 14
    ctx.font = "normal 16px Arial"
    ctx.fillText(this.userText.substr(14 * num + aa, aa), 0this.heightImg + 38)
    for (let a = 0; a <= num; a++) {
      ctx.font = "normal 16px Arial"
      ctx.fillText(this.userText.substr(a * 1414), 0this.heightImg + 40 + a * 16)
    }
   
  },
  saveCnavs(){
    wx.saveImageToPhotosAlbum({
      filePaththis.saveTempFilePath,
      success:res=>{
        wx.showModal({
         title:"图片保存成功!"
        })
      }
    })
  }
绘制出来的都没有问题,在保存到相册中也没有任何错误,就是保存的图片全都是空白的,这是什么错误
2 回复

你好,麻烦提供出现问题的具体机型、微信版本号、系统版本号,以及能复现问题的代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)

点击的保存的时候再去生成图片 也就是你的长按事件那一块

在长按的时候去canvasToTempFilePath 然后在success 里面去 saveImageToPhotosAlbum

回到顶部