Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
Canvas borders between rectangles

I have made a QR-code generator.

It takes a string of spaces and '#' to generate an image using the canvas. This string is given to the following function as the text parameter:

export const drawQR = (text) => {
    // Set up canvas and go to top left
    let canvas = document.getElementById("qr-code-canvas");
    let ctx = canvas.getContext("2d");
    ctx.lineWidth = "1";
    // ctx.moveTo(0,0)

    // calculate box height and width
    let lines = text.split('\n');
    let boxes_h = lines.length;
    let chars_first = Array.from(lines[0]);
    let boxes_w = chars_first.length;
    let width = canvas.clientWidth
    let height = canvas.clientHeight;

    let box_height = height/boxes_h;
    let box_width = width/boxes_w;

    // Keep track of current position
    let x = 0;
    let y = 0;

    lines.forEach((line) => {
        Array.from(line).forEach((char) => {
            if (char == " ") {
                ctx.beginPath();
                ctx.fillStyle = "white";
                ctx.rect(x, y, box_width, box_height);
                ctx.fill();
            } else if (char == "#") {
                ctx.beginPath();
                ctx.fillStyle = "black";
                ctx.rect(x, y, box_width, box_height);
                ctx.fill();
            } else {
                console.error(`error: unkown character in QR code: ${char}`)
            }
            x += box_width;
        });
        x = 0;
        y += box_height;
    });
}

Now I just draw a white rectangle for each space in the string and a black one for each '#' in the string. A new line goes down one box and starts back at the left again.

The problem I have with this is that there are small borders between the boxes: QR code 1

I have tried making the boxes bigger:

ctx.rext(x, y, box_width + 1, box_height + 1);

This works pretty well for bigger boxes, but when the boxes get smaller, I start to get artifacts (zoom in on the top left box for example):

QR code 2

Drawing a border for each rectangle has a similar result.

Does anyone know how to fix these issues?

Thank you in advance for your answers, Jonas

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!