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()
}
相关推荐
不听话坏16 小时前
Ignition篇(下 一) 动态执行前的事情
开发语言·前端·javascript
小二·17 小时前
React 19 + Next.js 15 现代前端开发实战:App Router / Server Components / 流式渲染
前端·javascript·react.js
CHNE_TAO_EMSM19 小时前
Android studio 打开文件时自动下载源码
前端·javascript·android studio
竹林81821 小时前
从 ethers.js 迁移到 Viem:一个签名验证 Bug 让我彻底放弃旧爱
javascript
你挚爱的强哥21 小时前
Vue2 实现 1.5s 十连击监听(连续点击若干次),封装通用可复用点击检测工具,不用 data!Vue 封装通用连击监听方法,支持自定义时长与点击次数
前端·javascript·vue.js
半个落月1 天前
用 LangChain.js 手写一个能读写文件和执行命令的 Mini Cursor
javascript·人工智能·后端
天外天-亮1 天前
HBuilder X 使用 uview-plus 方式
开发语言·javascript·hbuilder x·uview-plus
我有满天星辰1 天前
Vue项目脚手架之争:create-vue与Vue CLI全面对比
前端·javascript·vue.js
多加点辣也没关系1 天前
JavaScript|第9章:对象 — 基础
开发语言·javascript·ecmascript
我有满天星辰1 天前
Vue 2 与 Vue 3 计算属性完全指南:从 Options API 到组合式 API 的演进
前端·javascript·vue.js