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()
}
相关推荐
默_笙2 小时前
🚓 分诊台与拆题术:让 RAG 学会判断和规划
前端·javascript
呃呃呃呃ex2 小时前
10. 现代前端工程化:ES6 React 项目实战与原理解析
前端·javascript
浪遏2 小时前
D2C 系统架构复盘:从设计稿到代码,我们踩过的坑和最终方案
前端·javascript·后端
Blanche15002 小时前
Webpack 构建流程解析
javascript·面试
Flynt2 小时前
官方说一个破折号拖慢整段高亮,我在 Node 里验证了一遍:机制是真的,2.8 倍没跑出来
javascript·性能优化·v8
默_笙2 小时前
🚗 把小说装进数据库了:我的第一个 RAG,和它的五个硬伤
前端·javascript
像我这样帅的人丶你还2 小时前
📱iPhone Duo 开屏动画咋实现的?
javascript·webgl·three.js
Leslie1652 小时前
把 SQL 性能诊断接入模型 API:从谓词分析到可验证优化
javascript
gnip2 小时前
UniApp 内嵌 H5 通信全攻略
前端·javascript
用户6802659051192 小时前
企业电脑统一管理怎么做?2026企业终端统一管理方法与工具推荐
javascript·后端·面试