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()
}
相关推荐
程序猿的程6 小时前
开源一个 React 股票 K 线图组件,传个股票代码就能画图
前端·javascript
大雨还洅下6 小时前
前端JS: 虚拟dom是什么? 原理? 优缺点?
javascript
唐叔在学习6 小时前
[前端特效] 左滑显示按钮的实现介绍
前端·javascript
青青家的小灰灰7 小时前
深入理解事件循环:异步编程的基石
前端·javascript·面试
前端Hardy8 小时前
HTML&CSS&JS:打造丝滑的3D彩纸飘落特效
前端·javascript·css
前端Hardy8 小时前
HTML&CSS&JS:丝滑无卡顿的明暗主题切换
javascript·css·html
UIUV9 小时前
node:child_process spawn 模块学习笔记
javascript·后端·node.js
烛阴10 小时前
Three.js 零基础入门:手把手打造交互式 3D 几何体展示系统
javascript·webgl·three.js
颜酱11 小时前
单调栈:从模板到实战
javascript·后端·算法
_AaronWong12 小时前
Electron 实现仿豆包划词取词功能:从 AI 生成到落地踩坑记
前端·javascript·vue.js