Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda