Javascript:使用canvas画二维码矩阵

更新于 2024-01-03

矩阵是由0和1组成的数组。
0-白色
1-黑色

/**
 * 
 * @param matrix Array
 * @param size Int
 * @param padding Int
 * @param transparentBackground Boolean
 * @returns {string}
 */
function createQRCodeCanvas(matrix, size, padding, transparentBackground) {
  size = size || 3
  padding = padding === undefined ? 3 : padding
  const width = Math.sqrt(matrix.length)
  const canvasWith = width * size + padding * 2

  const canvas = document.createElement('canvas')
  canvas.width = canvasWith
  canvas.height = canvasWith

  const ctx = canvas.getContext('2d')
  if(!transparentBackground) {
    ctx.fillStyle = 'rgb(255,255,255)'
    ctx.fillRect(0, 0, canvasWith, canvasWith)
  }
  ctx.fillStyle = 'rgb(0,0,0)'

  for (let y = 0; y < width; y++) {
    for (let x = 0; x < width; x++) {
      const point = y * width + x
      if (matrix[point] === 1) {
        ctx.fillRect(padding + x * size, padding + y * size, size, size)
      }
    }
  }
  return canvas.toDataURL()
}