0

I am drawing a chart

<canvas id="mychart" width="421" height="280" class="chartjs-render-monitor" style="display: block; width: 421px; height: 280px;"></canvas>

How do I get the height in javascript

Ihave tried this

var ctx = document.getElementById(params.placeHolder);
console.log(ctx.height)

It's returning 150 instead of 280

Anoop
  • 505
  • 8
  • 23
  • What is `params.placeHolder`? –  Dec 02 '20 at 01:13
  • Note that 300x150 are the default measurements of a canvas, so my first guess is you're logging some other canvas's height maybe. If I set `params.placeHolder` to `mychart`, your code works as expected. Still, getting the height like that is potentially unsafe; what is your goal here? –  Dec 02 '20 at 01:27

2 Answers2

1

You need to use the offsetHeight.

var ctx = document.getElementById("mychart");
console.log(ctx.offsetHeight)
<canvas id="mychart" width="421" height="280" class="chartjs-render-monitor" style="display: block; width: 421px; height: 280px;"></canvas>
Aristeidis Karavas
  • 1,891
  • 10
  • 29
1

Using jQuery, try with:

$('#mychart').height();

With pure JS, try some of these:

var ctx = document.getElementById(params.placeHolder).clientHeight;
var ctx = document.getElementById(params.placeHolder).offsetHeight;
var ctx = document.getElementById(params.placeHolder).scrollHeight;

.scrollHeight

clientHeight includes the height and vertical padding.

offsetHeight includes the height, vertical padding, and vertical borders.

scrollHeight includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.

Got this last response here

Dharman
  • 30,962
  • 25
  • 85
  • 135
Grazielle Carvalho
  • 423
  • 1
  • 3
  • 11