Javascript Canvas 问题 : Why do my points on the canvas not correspond properly to the height of the graph?

标签 javascript canvas plot points linegraph

我正在尝试使用看起来像典型折线图的 Canvas 制作折线图,并使用我们在代数中学到的典型笛卡尔坐标; 左下角0,0开始,x轴位置由要绘制的项目数决定。

但是,点的位置与输入不匹配(虽然图形的形状是正确的,表明我做对了)。我做错了什么?

我已经多次重写和调整转换公式

function newLineGraph(parent, width, height, dataArray) {
    //this makes the element using my own code, no observable error here
    var canvas = newCanvas(parent, width, height);
    var canvasContext = canvas.getContext("2d");

    var spaceBetweenEntries = width / dataArray.length;

    var largestNumber = findHighestNumber(dataArray);

    canvasContext.beginPath();
    canvasContext.moveTo(0, 0);

    var n = 0;
    while (dataArray[n]) {

        var x = spaceBetweenEntries * n;
        var y = height - dataArray[n];
        console.log("x,y", x, y);
        canvasContext.lineTo(x, y);
        n++;
    }
    canvasContext.stroke();

    return canvas;
}

The resulting graph

编辑:修复了图像,以便您可以看到 Canvas 大小

生成的图比预期的图小得多;例如 newLineGraph("body",55,45,[1,40,10]); 生成一个 Angular 落有一个小 ^ 形状的图形,而不是从底部开始。但是,控制台日志显示 "0 44""18.333333333333332 5","36.666666666666664 35" 我认为应该生成一个非常适合整个图表的图表。

最佳答案

第一个 lineTox 始终为 0,所以我假设第一行没有按照您的预期绘制。它更像是一个 |/\ 形状而不是 \/\。 像这样设置 x:

var x = spaceBetweenEntries * (n + 1);

编辑

正如您在此 fiddle 中看到的那样您的图表使用您发布的坐标在正确的点呈现。我按照预期的方式实现了 newCanvas 函数。那么我们是否遗漏了一些其他修改 Canvas widthheight 的代码?

function newCanvas(parent, width, height) {
  const canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;
  document.querySelector(parent).appendChild(canvas);
  return canvas;
}

关于Javascript Canvas 问题 : Why do my points on the canvas not correspond properly to the height of the graph?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57834276/

相关文章:

wpf - 使用带有 ItemsControl 的 ScrollViewer 和 Canvas 作为 ItemsPanel

javascript - 如何获取 Polymer/Web 组件中 Canvas 上单击/点击的坐标(在滚动容器内时)

python - seaborn : plotting graph from dataframe in loop not working as expected

python - 3D 绘图区域满足 matplotlib 中的不等式

python - 访问元组字典中所有元素的相同值

javascript - 错误 : Unknown provider - Karma, requirejs, Angular

javascript - React - 当 Prop 通过父状态更新时,子组件不会更新

javascript - 如何使用从 Servlet 发送并由 JavaScript 通过 Jquery 接收的数据来更改网页内容?

java - 如何在 Android 上旋转 Canvas 上的位图而不使其变形

javascript - 如何读取通过 cordova 文件插件写入的对象?