javascript - 如何在 Canvas 上制作带有条形图的图表,其中条形图具有 Canvas 的高度?

标签 javascript canvas charts html5-canvas height

我必须使用 vanilla JS 在 Canvas 上制作一个栏,而不是 Charts.js 或 jquery。对于 Canvas 尺寸来说,条形图太长,因此无法显示条形图的完整长度。如何缩放条形以使它们适合硬编码的 Canvas 高度?

提前致谢!

<!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>

最佳答案

这是获取canvas高度的方法:

document.getElementById('canvas').height

所以,这将是最下面点的坐标。 Canvas 顶部的坐标为 0。此函数计算给定百分比的坐标:

function percent(input, canvasHeight) {
    return canvasHeight - (canvasHeight * input / 100);
}

关于javascript - 如何在 Canvas 上制作带有条形图的图表,其中条形图具有 Canvas 的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58584113/

相关文章:

javascript - 仅缩放图像 JQuery 的点击部分

javascript - Angularjs拦截器导致错误

javascript - 使用 Canvas 在 promise 内裁剪图像不起作用

mysql - 图表与MySql的连接

jquery - 删除 Flot 饼图中切片之间的白线

javascript - Electron -ipcRenderer.send()的SetTimeout

javascript - 问题的 JSON 数组格式

javascript - 使用 createJS 获取对容器的缓存版本的引用

javascript - 我在使用 Canvas putImageData 从另一个 Canvas /图像(png)复制透明像素时遇到问题

c# - 如何将数据点快速添加到WPF图表