How to make canvas graph responsive?

Member

by orpha , in category: HTML & CSS , 5 months ago

How to make canvas graph responsive?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 5 months ago

@orpha 

To make a canvas graph responsive, you can follow these steps:

  1. Set the canvas width and height properties to a percentage value instead of a fixed pixel value:
1
2
3
var canvas = document.getElementById('graph');
canvas.width = '100%';
canvas.height = '100%';


  1. Add an event listener to the window object for the 'resize' event:
1
window.addEventListener('resize', resizeCanvas);


  1. Create a resizeCanvas function that adjusts the canvas dimensions whenever the window is resized:
1
2
3
4
5
6
7
function resizeCanvas() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  // redraw the graph on the resized canvas
}

resizeCanvas(); // call this function once initially to set the canvas dimensions


  1. Redraw the graph on the resized canvas by updating its data and re-rendering it. This step will vary depending on the specific graph library or code you are using.