Get the QR code canvas image with a customized background by downloading it

I am having trouble with downloading a QR code canvas image with a background. The download works fine, but my device is unable to scan the code properly due to an incomplete border. I need to add a white background behind it to make it larger.

Current image:

Expected image:

This is my current code:

<a id="download-qr">
<div id="qrCode"></div>
  $('#qrCode').qrcode({
     render: "canvas",
     minVersion: 8,
     maxVersion: 8,
     ecLevel: 'M',
     size: 200,
     mode: 0,
     text: code,
  });

  var canvas = $("#qrCode").children(":first")[0];
  var ctx = canvas.getContext("2d");
  ctx.globalCompositeOperation = 'destination-over';
  ctx.fillStyle = "white";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  var img = canvas.toDataURL("image/jpeg");
  var dl = document.getElementById('download-qr');
  dl.setAttribute('href', img);
  dl.setAttribute('download', 'test.jpg');

Your assistance would be greatly appreciated. Thank you very much.

Answer №1

To enhance your ctx object, consider incorporating a white border.

ctx.lineWidth = 5;
ctx.strokeStyle = "white";
ctx.stroke();

Answer №2

Are you looking for a way to generate QR codes in your project? If not, consider using Qurious. It offers its own padding option and can generate QR codes directly on a canvas element.

To implement Qurious, add the following script to the head section of your HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js"></script>

Next, include the following HTML code to create the canvas where the QR code will be displayed:

<canvas id="qrCode"></canvas>

Then, insert the provided JavaScript code to generate and download the QR code based on a specific value:

const makeQR = (your_value) => {
      let qrcodeContainer = document.getElementById("qrCode");
        qrcodeContainer.innerHTML = "";
        new QRious({
          element: qrcodeContainer,
          value: your_value,
          size: 600,
          padding:50,
        }); // generate QR code
        
        var link = document.createElement('a');
        link.download = 'your_file.png';
        link.href = document.getElementById('qrCode').toDataURL()
        link.click(); // download it
        
    }

makeQR("your value")

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function req.isAuthenticated() always returns false and never evaluates to true

My goal is to create user authentication using the following code: userRouter.post("/login", passport.authenticate("local", { session: false }), (req, res) => { if (req.isAuthenticated()) { const { _id, username } = req.user; const t ...

Prevent repeating the same table header multiple times when generated dynamically with jQuery

I have an array called groups which contains name and regid. I want to display the name key as the column header of a table. To achieve this, I implemented the following code: var Name = v.name; var regId = v.regid; var rowStr = '<th d ...

Checking if children have certain text using jQuery

My task involves filtering an HTML table. In order to accomplish this, I have created an 'each' callback for all 'tr' elements and check if any of their children contain a specific pattern. $("#filter").keypress(function() { var fi ...

Using Javascript, populate an array with Enum variable values

Hey there! I've got this code that creates an array from an enum variable in JavaScript, but it's looking a bit old and clunky. I'm curious if any JavaScript or jQuery experts out there have a cleaner (best practice) approach for achieving ...

Extracting information from a webpage by using Javascript to locate and interact

Seeking a way to retrieve the src attribute from an audio tag dynamically inserted into the DOM by third-party JavaScript without the ability to modify it. The goal is to back up these sounds by capturing their sources on the server side across multiple pa ...

Is there a way to position the text to the right and the image to the left?

I have written the following code: <!DOCTYPE html> <html> <head> <title>UMass Boston Computer Science Club About page</title> <link href='https://fonts.googleapis.com/css?family=Chakra Petch' rel='sty ...

Saving vast array in MongoDB

I am currently working on a personal project that involves implementing a search feature. My setup includes using typeahead.js with a REST api created in expressJS and mongoDB. I could use some guidance on two particular challenges I am facing. While my ba ...

Add a fresh widget to the DOJO attachment point without overwriting

Here is some code I have: postCreate: function() { this.items.forEach(lang.hitch(this, function(item) { new SideNavigationItem({ name: item.name }, this.container); })); } This code snippet ...

What is the process for converting CSS to SASS when using arithmetics in selectors?

Is there a more efficient way to convert the following CSS code into SASS? div#block-views-news-block, div#block-views-news-block-1, div#block-views-news-block-3, div#block-views-news-block-4 { margin: 0; padding: 0; } I attempted the following: div ...

Utilizing YouTube API information with AngularJS

I am currently working on a project where I need to fetch all the playlists from a specific channel and then display the name of each playlist in my AngularJS application. var myApp = angular.module('app', ['ngResource']); myApp.facto ...

Using Ajax to dynamically generate column headers in Datatables

Is there a way to create a header title from an ajax file? I've been trying my best with the following code: $('#btntrack').on('click', function() { var KPNo = $('#KPNo').val(); var dataString = & ...

Position the div in the center, but for smaller sizes, switch to aligning

My current layout setup is as follows: Left side bar with a width of 200px and positioned at left: 0; Center section with a width of 700px and positioned at left: 250px; Right side bar with a width of 200px and positioned at right: 10px; While this arra ...

The ajax response is returning the entire page's html code instead of just the text content from the editor

I've been working with CKEditor and I'm using AJAX to send the editor's content via POST method. However, when I try to display the response in a div, the HTML for the entire page is being returned instead of just the editor's content. ...

Interrupt the current with an external factor

I am working with a flexbox layout that currently looks like this: https://i.stack.imgur.com/ULHEk.jpg My main question now is whether there is a way to disrupt the flow externally from the flexbox, so that the blocked element can move to the next positi ...

Instructions for showcasing a 404 error page in the event that a back-end GET request to an API fails due to the absence of a user. This guide will detail the process of separating the

I am currently working on an application that combines JavaScript with Vue.js on the front-end and PHP with Laravel on the back-end. When a GET request is made from the front-end to the back-end at URL /getSummoner/{summonerName}, another GET request is t ...

A div containing a form, with the form being visually integrated within the div

Hi everyone, this is my first post here and I've tried to search extensively before asking this question. I've attempted to use the following examples without success: jquery submit form and then show results in an existing div Form submit ...

Exploring dependency injection in Angular 1 using a blend of JavaScript and TypeScript

I'm currently working on integrating TypeScript into an existing Angular 1.5 application. Despite successfully using Angular services and third-party services, I am facing difficulties in injecting custom services that are written in vanilla JavaScrip ...

Troubles with Angular Js: Issues with using $http.put with absolute URLs

Having an issue with $http.put in AngularJS. My server is built with Node.js and my app is in AngularJS. I am trying to make requests from AngularJS to access data on the Node.js server (same host). This code works: $http.put("/fraisforfait", elements); ...

The dropdown within the modal is proving elusive for Selenium to locate

I am attempting to choose a value from the dropdown menu labeled 'ddl_settpymtaction' using Selenium, but unfortunately it seems to be unable to locate it within the modal where it is located. CSS: https://i.stack.imgur.com/3YWQu.png Selenium ...

Is it necessary to always include all styles for jQuery UI separately in my project?

While reading various articles, I have noticed a common suggestion to explicitly bundle each jQueryUI .css file, such as the answer provided on How to add jQueryUI library in MVC 5 project?. However, upon examining the .css files within the Content/themes/ ...