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

123
Views
Responsive canvas content to fit different screen sizes

I have a canvas element with 3 circles that is shown well and fit on large screens. But with smaller screens, The content goes outside of the canvas.

HTML:

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

JS:

const canv = document.getElementById('canvas'),
      context = canv.getContext('2d');

    //Set canvas width and height equals to screen width and height
    canv.height = window.innerHeight;
    canv.width = window.innerWidth;
    
//Draw circles
for(let i = 300; i < 950; i+=300){
    if(i < 900){
        context.fillRect(i + 150, 350, 100, 10);
    }
    context.beginPath();
    context.arc(i + 50, 350, 100, Math.PI * 2, false);
    context.stroke();
}

Here is a live fiddle: https://jsfiddle.net/ep3yjs5q

How to make the 3 circles responsive? Can I use percentages for dimensions?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Yes you can use percentages. Based on the code you've provided I assume your calculations for the size and position of the circles is based on a canvas that has a width of 1300 pixels.

Let's do the math:

  • your circle's diameter is 200 pixels | 200 / 1300 = 0.1539
  • the spacing between them is 300 pixels | 300 / 1300 = 0.2307

With this information we can calculate the appropriate width/height/spacing for the canvas's actual size:

const canv = document.getElementById('canvas'),
  context = canv.getContext('2d');

canv.height = window.innerHeight;
canv.width = window.innerWidth;

let diameter = (200 / 1300) * canv.width;
let spacing = (300 / 1300) * canv.width;
let barHeight = (30 / 1300) * canv.height;
let startX = canv.width / 2 - spacing;
let startY = canv.height / 2;
for (let i = 0; i < 3; i++) {
  if (i < 2) {
    context.fillRect(startX + i * spacing + diameter / 2, startY, spacing - diameter, barHeight);
  }

  context.beginPath();
  context.arc(startX + i * spacing, startY, diameter / 2, Math.PI * 2, false);
  context.stroke();
  context.closePath();
}
<canvas id="canvas" style="background: #dddddd"></canvas>

about 4 years ago · Juan Pablo Isaza Report
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!