Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda