1
hao
2025-03-27 e610e1c17f62b423a717fadaaa7b139d02857793
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const Utils = require('./utils')
 
function clearCanvas (ctx, canvas, size) {
  ctx.clearRect(0, 0, canvas.width, canvas.height)
 
  if (!canvas.style) canvas.style = {}
  canvas.height = size
  canvas.width = size
  canvas.style.height = size + 'px'
  canvas.style.width = size + 'px'
}
 
function getCanvasElement () {
  try {
    return document.createElement('canvas')
  } catch (e) {
    throw new Error('You need to specify a canvas element')
  }
}
 
exports.render = function render (qrData, canvas, options) {
  let opts = options
  let canvasEl = canvas
 
  if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
    opts = canvas
    canvas = undefined
  }
 
  if (!canvas) {
    canvasEl = getCanvasElement()
  }
 
  opts = Utils.getOptions(opts)
  const size = Utils.getImageWidth(qrData.modules.size, opts)
 
  const ctx = canvasEl.getContext('2d')
  const image = ctx.createImageData(size, size)
  Utils.qrToImageData(image.data, qrData, opts)
 
  clearCanvas(ctx, canvasEl, size)
  ctx.putImageData(image, 0, 0)
 
  return canvasEl
}
 
exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {
  let opts = options
 
  if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
    opts = canvas
    canvas = undefined
  }
 
  if (!opts) opts = {}
 
  const canvasEl = exports.render(qrData, canvas, opts)
 
  const type = opts.type || 'image/png'
  const rendererOpts = opts.rendererOpts || {}
 
  return canvasEl.toDataURL(type, rendererOpts.quality)
}