收藏
回答

canvas的draw方法在循环里为啥只执行一次?

我想在上传图片时,给图片加上水印。目前的方法是本地上传图片,获取图片数组。然后循环这个数组,利用canvas给每张图片加上水印。最后获得加上水印的图片数组。

但是在循环时发现ctx.draw()方法只执行一次。是什么情况


回答关注问题邀请回答
收藏

1 个回答

  • 郑旭东
    郑旭东
    2020-04-29

    你不亮代码,鬼知道什么情况。

    提醒下,draw的并发性能很差,最好是一张一张递归来执行,打完一张水印再打另一张。

    然后可以用新的canvas 2D接口,ctx.drawImage,老接口不再维护了。

    2020-04-29
    有用 1
    回复 5
    • Admin ²º²³
      Admin ²º²³
      2020-04-29
      对的,经验之谈,附议。
      2020-04-29
      回复
    • 肖本松
      肖本松
      2020-04-29
      this.getImage().then(res=>{
         return new Promise((resolve, reject) => {
          res.map((item)=>{
           uni.getImageInfo({
            src: item,
            success: (ress) => {
             this.nowTime = formatDate(new Date())
             let ctx = uni.createCanvasContext('firstCanvas');
             let width = ress.width;
             let height = ress.height;
             let ratio = width/height;
             let screenWidth = uni.getSystemInfoSync().windowWidth;
             let screenHeight = uni.getSystemInfoSync().windowHeight;
             if(ratio>=1){
              width = width>screenWidth ? screenWidth : width;
              height = parseInt(width/ratio)
             }else{
              height = height>screenHeight ? screenHeight : height;
              width = parseInt(height*ratio)
             }
            
             that.canvasWidth = width;
             that.canvasHeight = height;
             //将图片src放到cancas内,宽高为图片大小
             ctx.drawImage(item, 0, 0, width, height)
             //将声明的时间放入canvas
             ctx.setFontSize(12) //注意:设置文字大小必须放在填充文字之前,否则不生效
             //设置字体颜色
             ctx.setFillStyle('#fa436a')
             ctx.fillText(`员工:${this.userInfo.user}`, 10, 20);
             ctx.fillText(`时间:${this.nowTime}`, 10, 40);
             console.log('canvas循环前');
             console.log(ctx);
             ctx.draw(false, function() {
              debugger;
              console.log('获取循环路径');
              uni.canvasToTempFilePath({
               canvasId: 'firstCanvas',
               success: (resss) => {
                that.imgRmarkList.push(resss.tempFilePath);
               },
               fail: (e) => {
                reject(e);
                console.log(e)
               }
              })
             })
            }
           })
           resolve(that.imgRmarkList);
          })
         })
        })
      2020-04-29
      回复
    • 郑旭东
      郑旭东
      2020-04-29回复肖本松
      大概看了一下,这是第一次都不一定执行完,循环接着就开始弄了?还是先试试改成一张一张弄吧。里面很多行为是异步的,循环并发处理会出问题。
      2020-04-29
      回复
    • 肖本松
      肖本松
      2020-04-29
      嗯,谢谢,我试试
      2020-04-29
      回复
    • Serendipity
      Serendipity
      2021-05-21回复肖本松
      解决了吗
      2021-05-21
      回复
登录 后发表内容
问题标签