How do I create a QR code for my website?
Generate QR Code for Your Website
This section demonstrates how to create a QR code that links directly to your website using the `qr-generator` library.
Scenario 1: Physical Marketing Materials
Enhance your print materials by allowing customers to instantly access your website. Simply scan the QR code below to visit our example website.
To generate your own QR code, you would typically use a server-side script or a client-side JavaScript implementation similar to the one outlined below.
Client-Side JavaScript Implementation (Conceptual)
This code snippet illustrates how you might use a client-side JavaScript library (assuming `qr-generator` is bundled or imported).
import QRCode from 'qr-generator'; // Or use
async function generateAndDisplayQRCode(url, elementId) {
try {
const qr = new QRCode({
text: url,
errorCorrectionLevel: 'M',
type: 'image/png', // For use in an img tag
margin: 1,
scale: 8
});
const dataURL = await qr.toDataURL();
document.getElementById(elementId).src = dataURL;
} catch (error) {
console.error('Error generating QR code:', error);
document.getElementById(elementId).alt = 'Error generating QR code';
}
}
// Example usage:
const websiteUrl = 'https://www.example.com'; // Replace with your actual website URL
window.onload = () => {
generateAndDisplayQRCode(websiteUrl, 'website-qr-code');
};
Server-Side Node.js Implementation (Conceptual)
For server-side generation, you would save the QR code as a file or serve it directly.
const QRCode = require('qr-generator');
const fs = require('fs');
async function createWebsiteQRFile(url, filePath) {
try {
const qr = new QRCode({
text: url,
errorCorrectionLevel: 'M',
type: 'png',
margin: 1,
scale: 8
});
const qrImageBuffer = await qr.toBuffer();
fs.writeFileSync(filePath, qrImageBuffer);
console.log(`QR code saved to ${filePath}`);
} catch (error) {
console.error('Error generating QR code file:', error);
}
}
// Example usage:
// createWebsiteQRFile('https://www.example.com', 'website_qr_physical.png');
By scanning this QR code, users can instantly navigate to https://www.example.com, increasing engagement with your online presence.