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()
}
相关推荐
Youyzq7 小时前
css样式用flex 布局的时候元素尺寸展示不对
前端·javascript·css
大雨倾城7 小时前
网页端和桌面端的electron通信Webview
javascript·vue.js·react.js·electron
yilan_n7 小时前
【UniApp实战】手撸面包屑导航与路由管理 (拒绝页面闪烁)
前端·javascript·vue.js·uni-app·gitcode
Highcharts.js7 小时前
官方文档|Vue 集成 Highcharts Dashboards
前端·javascript·vue.js·技术文档·highcharts·看板·dashboards
Misha韩7 小时前
vue3+vite模块联邦 ----子应用中页面如何跳转传参
前端·javascript·vue.js·微前端·模块联邦
乖女子@@@7 小时前
01ReactNative-环境搭建
javascript·react native·react.js
开发者小天7 小时前
react中的使用useReducer和Context实现todolist
前端·javascript·react.js
老前端的功夫7 小时前
Webpack打包机制与Babel转译原理深度解析
前端·javascript·vue.js·webpack·架构·前端框架·node.js
by__csdn7 小时前
javascript 性能优化实战:垃圾回收优化
java·开发语言·javascript·jvm·vue.js·性能优化·typescript