使用数组(JavaScript)在Canvas上绘制点

时间:2017-02-06 11:42:48

标签: javascript arrays canvas

所以我的老师希望我们创建一个画布。他给了我们一些我无法理解的令人困惑的指示。

  

使用路径绘制数组中的点并将其显示为a   线形图。调整数组的每个成员的x坐标   调整y坐标以显示每个成员的值。记住,   画布中的y坐标将0放在屏幕顶部,这样就可以了   需要从图形高度+边框中减去每个数组值   大多数折线图显示相对于图表底部的数据   而不是顶部。 x坐标应由单位调整   每个数组值的间距。我强烈建议使用for   循环。

我真的想解释这意味着什么以及如何做到这一点。

HTML:

<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <canvas id="myCanvas" width="600" height="600" style="border: 1px solid #ddd;">Your browser does not support the HTML5 canvas tag
     </canvas>
    <script src="script.js">
    </script>
</body>
</html>

Java脚本:

graph();

function graph() {
  var canvas = document.getElementById("myCanvas");
  var theContext = canvas.getContext("2d");
  var sales = [52, 48, 74, 31, 47, 25, 67, 78, 45, 15, 85];
  var width = 300;
  var height = 100; 
  var uSpacing = 10;
  var border = 20;
  var scalar = 100;

  theContext.strokeRect(border, border, width, height)
  theContext.beginPath();
  theContext.moveTo(100,100);
  theContext.lineTo(52,48);
  theContext.stroke();
}

1 个答案:

答案 0 :(得分:3)

喜欢这个吗?

&#13;
&#13;
graph();

function graph() {
  var canvas = document.getElementById("myCanvas");
  var theContext = canvas.getContext("2d");
  var sales = [52, 48, 74, 31, 47, 25, 67, 78, 45, 15, 85];
  var width = 300;
  var height = 100;
  var uSpacing = 10;
  var border = 20;
  var scalar = 100;
  var offset = (1 / (sales.length - 1)) * width;

  theContext.strokeRect(0, 0, width, height)

  theContext.beginPath();
  theContext.moveTo(0, sales[0]);
  for (var x = 1; x < sales.length; x++) {
    theContext.lineTo(x * offset, 100 - sales[x]);
  }
  theContext.stroke();
}
&#13;
<canvas id="myCanvas" width="600" height="600" style="border: 1px solid #ddd;">Your browser does not support the HTML5 canvas tag
</canvas>
&#13;
&#13;
&#13;

修改

哎呀,忘了翻转Y轴。

持续更新

只是为了好玩^^

&#13;
&#13;
var sales = [52, 48, 74, 31, 47, 25, 67, 78, 45, 15, 85];

function graph() {
  var canvas = document.getElementById("myCanvas");
  var theContext = canvas.getContext("2d");
  var width = 300;
  var height = 100;
  var uSpacing = 10;
  var border = 20;
  var scalar = 100;
  var offset = (1 / (sales.length - 1)) * width;

  theContext.clearRect(0, 0, width, height)
  theContext.strokeRect(0, 0, width, height)

  theContext.beginPath();
  theContext.moveTo(0, sales[0]);
  for (var x = 1; x < sales.length; x++) {
    theContext.lineTo(x * offset, 100 - sales[x]);
  }
  theContext.stroke();
}

setInterval(function() {
  sales.push(Math.random() * 100);
  if (sales.length > 100) {
    sales = sales.slice(sales.length - 100);
  }
  graph();
}, 1000/24)

graph();
&#13;
<canvas id="myCanvas" width="600" height="600" style="border: 1px solid #ddd;">Your browser does not support the HTML5 canvas tag
</canvas>
&#13;
&#13;
&#13;