§ What we want

Ability to specify the text content for the QR code

Display it on the browser

Ability to open the QR code in a new tab as an image

After doing a quick research on QR code generators I found this one called node-qrcode.

Unlike the others I saw, this one looks maintained, well documented and has a pretty good list of features.

We’ll use this as the basis for our QR code generator.

§ Interactive demo

QR code generator Type some text here 0 Reset Open

§ The code

< template lang = "pug" > v-card(raised).accent--border.my-12 v-card-title v-icon(color="secondary" left) mdi-qrcode span QR code generator v-card-text v-text-field( v-model="qrText" clearable counter filled label="Type some text here" @input="generateQrCode" ) .d-flex.justify-center(v-if="qrSrc") img.image-preview(:src="qrSrc") v-card-actions v-btn( color="accent" :disabled="!qrSrc" @click="reset" ) v-icon(left) mdi-close span Reset v-spacer v-btn( color="primary" :disabled="!qrSrc" @click="openInNewWindow" ) v-icon(left) mdi-open-in-new span Open </ template > < script > import qrCode from 'qrcode' export default { data () { return { qrText : '' , qrSrc : null } }, beforeDestroy () { this .reset() }, methods : { createObjectUrl (err, canvas) { if (!err) { canvas.toBlob( ( blob ) => { this .qrSrc = window .URL.createObjectURL(blob) }) } else { console .warn( 'generateQrCode:ERROR' , err) } }, generateQrCode () { if (! this .qrText) { return } window .URL.revokeObjectURL( this .qrSrc) qrCode.toCanvas( this .qrText, {}, this .createObjectUrl) }, openInNewWindow () { window .open( this .qrSrc) }, reset () { window .URL.revokeObjectURL( this .qrSrc) this .qrSrc = null this .qrText = '' } } } </ script > < style lang = "sass" scoped > .accent--border border : 1 px solid var ( --v-accent-base ) .image-preview display : block max-width : 100% </ style >

§ Display in browser

First we need to use the qrCode.toCanvas() function to get a hold of a canvas element that contains the QR code embedded in it.

Then, we use canvas.toBlob() to get the image data in a format that can be taken by window.URL.createObjectURL() that will result in something we can put in a :src attribute on an img element.

§ Open in new tab

This is very easy, you just need to call window.open() passing to it the result from the window.URL.createObjectURL() call.

Don’t forget to call window.URL.revokeObjectURL() !

§ Object URLs vs data URLs

Using object URLs over data URLs has some really cool advantages:

You don’t increase the file size by one third since you don’t Base64 encode the image data.

You are able to open a new tab with window.open() if you pass an object URL to it. You can’t do that with data URLs.

There is one important caveat though: