Javascript:使用canvas画二维码矩阵

矩阵是由0和1组成的数组。

0-白色

1-黑色

javascript 复制代码
/**
 * 
 * @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()
}
相关推荐
GISer_Jing4 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩4 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车5 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
丷丩9 小时前
MapLibre GL JS第19课:实时更新要素
前端·javascript·gis·map·mapbox·maplibre gl js
xiaohua0708day9 小时前
Lodash库
前端·javascript·vue.js
突然好热10 小时前
TS 调试技巧
前端·javascript·typescript
h64648564h10 小时前
Flutter 国际化(i18n)全指南:一键切换中/英/日多语言
前端·javascript·flutter
丷丩11 小时前
MapLibre GL JS第8课:禁用滚动缩放
javascript·mapbox·maplibre gl js
kyriewen13 小时前
面试8家前端岗位后,我发现了一个残酷的事实:AI不是加分项,是门槛
前端·javascript·面试
MageGojo16 小时前
做节日活动页时,如何用 API 快速生成对联内容
javascript·python·节日·对联生成