Javascript:使用canvas将二维码矩阵转化为图片
矩阵是由0和1组成的数组。
0-白色
1-黑色
/*** * @param matrix Array* @param size Int* @param padding Int* @param transparentBackground Boolean* @returns {string}*/
function createQRCodeCanvas(matrix, size, padding, transparentBackground) {size = size || 3padding = padding === undefined ? 3 : paddingconst width = Math.sqrt(matrix.length)const canvasWith = width * size + padding * 2const canvas = document.createElement('canvas')canvas.width = canvasWithcanvas.height = canvasWithconst 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 + xif (matrix[point] === 1) {ctx.fillRect(padding + x * size, padding + y * size, size, size)}}}return canvas.toDataURL()
}