将字符串转化为条形码,在将canvas转化为图片

利用jsBarCode可将字符串转为条形码

先创建一个画布

<canvas id="barcode" class="barcode1"></canvas>

再用JsBarcode进行绘画

import JsBarcode from 'jsbarcode'
// displayValue是设定是否默认展示二维码对应的文字
JsBarcode("#barcode", 'EMS22121212', {displayValue: false});

canvas转img

主要是用toDataURL将canvas解析为img标签src所需要的字段

再对元素进行增删操作,是img放入页面dom

function canvasToImg (className, height) {
      const barcode = document.getElementsByClassName(className)[0]
      const barcodeFather = barcode.parentNode
      let img = document.createElement('img')
      img.src = barcode.toDataURL("image/png")
      barcodeFather.insertBefore(img, barcode)
      if (height) {
        img.style.height = `${height}px`
      } else {
        img.width = barcode.width;
        img.height = barcode.height;
      }
      barcodeFather.removeChild(barcode);
    }
posted @ 2021-05-28 11:17  Monday1997  阅读(322)  评论(0编辑  收藏  举报