Skip to content

Commit

Permalink
Implement canvas.renderToBlob() function to export QR Code as blob …
Browse files Browse the repository at this point in the history
…data
  • Loading branch information
jozefizso committed Oct 20, 2024
1 parent 049879d commit b2bc8c5
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/renderer/canvas.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,21 @@ exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {

return canvasEl.toDataURL(type, rendererOpts.quality)
}

exports.renderToBlob = function renderToBlob (cb, qrData, canvas, options) {
let opts = options

if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
opts = canvas
canvas = undefined
}

if (!opts) opts = {}

const canvasEl = exports.render(qrData, canvas, opts)

const type = opts.type || 'image/png'
const rendererOpts = opts.rendererOpts || {}

canvasEl.toBlob(cb, type, rendererOpts.quality)
}
54 changes: 54 additions & 0 deletions test/unit/renderer/canvas.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,57 @@ test('CanvasRenderer renderToDataURL to provided canvas', function (t) {

t.end()
})

test('CanvasRenderer renderToBlob', function (t) {
// Mock document object
global.document = {
createElement: function (el) {
if (el === 'canvas') {
const canvas = createCanvas(200, 200)

// The `HTMLCanvas` element has a `toBlob()` method
// to export content as image bytes. The equivalent
// methos in `canvas` library is the `toBuffer()`.
canvas.toBlob = (cb, mimeType, config) => {
const buffer = canvas.toBuffer(mimeType, config)
const blob = new Blob([buffer], { type: mimeType })
cb(blob)
}

return canvas
}
}
}

t.plan(6)

const sampleQrData = QRCode.create('sample text', { version: 2 })
let imageBlob

t.doesNotThrow(function () { CanvasRenderer.renderToBlob((blob) => {}, sampleQrData) },
'Should not throw if canvas is not provided')

t.doesNotThrow(function () {
CanvasRenderer.renderToBlob((blob) => {
imageBlob = blob

t.type(imageBlob, 'Blob',
'Should return a Blob object')

t.equal(imageBlob.toString('base64'), '[object Blob]',
'Blob data cannot be converted to base64 econding')

t.equal(imageBlob.size % 4, 0,
'Should have a correct size')

t.equal(imageBlob.type, 'image/png',
'Should have a correct type value')
}, sampleQrData, {
margin: 10,
scale: 1,
type: 'image/png'
})
}, 'Should not throw with options param')

global.document = undefined
})

0 comments on commit b2bc8c5

Please sign in to comment.