Resize Canvas html to fit the inner content

Viewed 36

I am trying to record audio and draw the bars on canvas. But I am stuck on resizing the canvas according to the length of bars that are there. Following is the JS for all the work that is being done. I tried adding function to resize canvas, and override the canvas width but none is working. css width:auto; is also not working. Following is the function That I have used to resize canvas according the to BARS length that are drawn. I tried to override the canvas width inside stop function [Current Visual of Bars inside canvas][1]

Following code can be tested in this codepen https://codepen.io/smashingmag/pen/qBVzRaj

function resizeCanvas() {
    CANVAS.width = BARS.length;
  console.log(CANVAS.width);
  }
resizeCanvas();

//Getting and initializing canvas from html to create bars 
    const CANVAS = document.querySelector('canvas')
    const DRAWING_CONTEXT = CANVAS.getContext('2d')
//setting canvas height and width and bars configuration
    CANVAS.width = CANVAS.offsetWidth
    CANVAS.height = CANVAS.offsetHeight
    
    const CONFIG = {
      fft: 2048,
      show: true,
      duration: 0.8,
      fps: 100,
      barWidth: 0.1,
      barMinHeight: 0.01,
      barMaxHeight: 0.3,
      barGap: 0.01,
    }
//here I am creating bars
const addBar = (volume = 100) => {
  const BAR = {
    x: CANVAS.width + CONFIG.barWidth / 2,
    // Note the volume is 0
    size: gsap.utils.mapRange(
      50,
      150,
      CANVAS.height * CONFIG.barMinHeight/3,
      CANVAS.height * CONFIG.barMaxHeight*3
    )(volume),
  }
const drawBars = () => {
  DRAWING_CONTEXT.clearRect(0, 0, CANVAS.width, CANVAS.height)
  for (const BAR of BARS) {
    drawBar(BAR)
  }
}

STOP.addEventListener('click', () => {
  if (recorder) recorder.stop()
  AUDIO.setAttribute('controls', true)
  AUDIO_CONTEXT.close()
  timeline.pause()
  SCRUB(START_POINT)
  var delayInMilliseconds = 1000; //1 second

setTimeout(function() {
  //Here i am getting the canvas image on console
  

  const img =  CANVAS.toDataURL("image/png");  
console.log(img);
}, delayInMilliseconds);
})

drawBars()
[1]: https://i.stack.imgur.com/JBBjT.png

1 Answers

I looked at your codepen and I think yours has a simple solution

function resizeCanvas() {
    CANVAS.style.width = BARS.length + "px";
    CANVAS.width = BARS.length;
}

This is just setting the CSS width property using javascript.

Doing CANVAS.width = 500 does not overwrite the CSS which tells it to be 300px. So it was still a CSS problem.

Related