vue项目将多张图片生成一个gif动图

当前做项目有一个需求是将多张图片生成一个gif动图的形式

类似下面图片几张图片叠加生成一个gif动图

图片涉及工作隐私,就不公开啦

 我们要引入一个gif.js的引入包,但是他没有直接引入的方式,只能从官方下载文件包,下载地址:git地址

下载好的包找到下面这个两个文件,引入到本地项目中去

将引入进来的两个包中的最后一行代码注释,避免映射

 然后:这里需要对gif.worker进行封装  

在gif.worker.js文件最后声明一个函数,将该文件除了注释部分的代码之外的所有代码复制变成文本,然后给一个变量  

生命的函数将复制的代码文本转化成 blob,然后转化成url的形式

export const gifWorkerContent = ` gif.worker.js文件代码(不要粘贴注释部分)  `

export const getGifWorker = () => {

  const blob = new Blob([gifWorkerContent])

  return window.URL.createObjectURL(blob)

}

然后在需要生成gif的单页面进行引入

 

引入完成之后, 

进行函数处理, 需要获取到所有的地图图片canvas元素,然后通过canvas转换成图片

toGif(item, index) {
      const _this = this
      this.imgs = []
      const temDiv = document.getElementById(item + index)
      this.mapOptionsList[item].forEach((items, index) => {
        const div = document.getElementById(item + index)
        const temimg = div.querySelector('canvas')
        this.imgs.push(temimg) // this.imgs这个数组是所有需要生成gif的图片的集合
      })
      // 生成GIF
      try {
        const { width, height } =
         temDiv.getBoundingClientRect() // 这里定义一下gif图片的大小
        const gif = new GIF({
          workers: 2,
          quality: 10,
          width,
          height,
          workerScript: getGifWorker() // 自定义worker地址
        })
        // 对所有的图片进行处理,利用canvas绘制图片
        this.imgs.forEach((img, index) => {
          const cv = document.createElement('canvas')
          cv.width = width
          cv.height = height
          const ctx = cv.getContext('2d')
          ctx.fillStyle = '#fff'
          ctx.fillRect(0, 0, width, height)
          ctx.drawImage(img, -20, 0, img.width, img.height)// 这里的img参数内容 要是canvas或者svg或者img的dom元素
          ctx.fillStyle = '#000' // 这里的fillStyle要注意却分大小写
          ctx.font = '20px normal'
          const temname = _this.mapOptionsList[item][index].title.name
          ctx.fillText(temname, 200, 25)
          ctx.fillStyle = '#000' // 这里的fillStyle要注意却分大小写
          ctx.font = '20px normal'
          const temtime = _this.mapOptionsList[item][index].title.time
          if (index == 0) {
            ctx.fillText(temtime, 110, 55)
          } else {
            ctx.fillText(temtime, 150, 55)
          }
          gif.addFrame(cv, { delay: 1000 })
        })
        // 渲染gif
        gif.render()
        // 图片合成后
        gif.on('finished', (blob) => {
          const a = document.createElement('a')
          a.href = URL.createObjectURL(blob)
          a.download = _this.mapOptionsList[item][index].title.text
          a.click()
          gif.abort()
        })
      } catch (error) {
        console.log(error)
      }
    },

 然后就可以生成gif图片啦 可以看一下下面的图片哦

图片涉及工作隐私就不公开啦

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值