如何在画布上制作带有横条且横条具有画布高度的图表?

问题描述 投票:1回答:1

我必须使用香草JS在画布上制作一个条形图,没有Charts.js或jquery。条形对于画布大小而言太长,因此无法显示条形的完整长度。如何缩放标尺,使其适合硬编码的画布高度?

提前感谢!

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>chart</title>
  </head>
  <body>
    <br>
    <br>
    <canvas id="canvas" width="400" height="400"></canvas>


<style> canvas { 
  border: 1px solid black; 
}
</style>

<script>

window.onload = function canvas() {
  let canvas = document.getElementById('canvas');
  let ctx = canvas.getContext('2d');
  let data = [['A', 439], ['B', 228.23], ['C', 2580.39], ['D', 279]];
  let barwidth = 50;
  let ygap = 30; 
  let bargap = 100; 
  let x = 50;

  y = canvas.height - ygap;

  canvas.width = data.length * (bargap) + x;

  ctx.moveTo(x - 5, y);
  ctx.lineTo(canvas.width, y); // Base line of graph 
  ctx.stroke();

  for (let i = 0; i < data.length; i++) {
    ctx.textAlign = 'left';
    ctx.textBaseline = 'top';
    ctx.fillStyle = 'black';
    ctx.fillText(data[i][0], x, y + 5); // Write base text for classes 

    ctx.beginPath();
    ctx.lineWidth = 2;
    y1 = y - data[i][1]; // Coordinate for top of the Bar 
    x1 = x;
    ctx.fillStyle = 'black';
    ctx.fillText(data[i][1], x1, y1 - 20); // text at top of the bar 

    ctx.fillStyle = 'black'; // fill Colur of bar  
    ctx.fillRect(x1, y1, barwidth, data[i][1]);// Filled bar

    x += bargap
  }
}
</script>

</body>
</html>
javascript canvas charts html5-canvas height
1个回答
0
投票

这是获取heightcanvas的方法:

document.getElementById('canvas')。height

因此,这将是最低点的坐标。画布顶部的坐标为0。此function计算给定百分比的坐标:

function percent(input, canvasHeight) {
    return canvasHeight - (canvasHeight * input / 100);
}
© www.soinside.com 2019 - 2024. All rights reserved.