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?
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:
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>