【发布时间】:2019-07-04 08:15:52
【问题描述】:
对 javascript 非常陌生,这是我的第一个项目!我正在使用 Html Canvas 和 Javascript 构建折线图。我有一个函数可以为 X 和 Y 坐标生成随机数,然后填充一个空数组。我想绘制点并在数组填充时连接它们。最终目标是构建一个基于点缩放的折线图。我知道代码有点乱(我很抱歉),还有其他问题,但我现在关注的问题是当代码运行时,它会绘制点 A,然后是 A B,然后是 A B C,然后是 A B C D,等等。我希望它逐步绘制点,所以它是点 A,然后是点 B,然后是点 C,等等。希望这是有道理的!
从我从其他人那里看到的,看起来最好的方法是引用数组中的前一个点,并确保 to 的行来自前一个点。我认为这就是我在这里所做的,或者至少是试图做的。
// Return the x pixel for a graph point
function getXPixel(val) {
return ((canvas.width - xMarg) / plotArray.length) * val + (xMarg);
}
// Return the y pixel for a graph point
function getYPixel(val) {
return canvas.height - (((canvas.height - yMarg) / getMaxY()) * val) - yMarg;
}
function plotPoints() {
ctx.strokeStyle = '#f00';
ctx.beginPath();
ctx.moveTo(getXPixel(0), getYPixel(plotArray[0].Y));
for (var i = 1; i < plotArray.length; i++) {
ctx.lineTo(getXPixel(i), getYPixel(plotArray[i].Y));
}
ctx.stroke();
label();
drawCircle();
}
function drawCircle() {
ctx.fillStyle = '#333';
for (var i = 0; i < plotArray.length; i++) {
ctx.beginPath();
ctx.arc(getXPixel(i), getYPixel(plotArray[i].Y), 4, 0, Math.PI * 2, true);
ctx.fill();
}
}
function setPlotHistory(){
var plotHistory = plotArray.length
plotArray[plotHistory.res] = {};
plotArray[plotHistory.moveToX] = plotArray.X;
plotArray[plotHistory.moveToY] = plotArray.Y;
}
runTest = setInterval(function() {
var res = { //Create object of results with each test
X: testsRun,
Y: getRandomNumber(10,150)
};
if (plotArray.length === 5) {
plotArray.shift();
}
plotArray.push(res); //put the result in the array
setPlotHistory(res);
document.getElementById('output').innerHTML = "Tests Run: " + testsRun;
testsRun++; //up the number of tests by one
plotPoints();
},testInt);
不确定,我应该提供多少信息,并且不想用整个代码填满页面,所以作为参考,您可以在这里查看我的完整代码https://jsfiddle.net/Crashwin/72vd1osL/3/
感谢任何帮助!
【问题讨论】:
标签: javascript canvas html5-canvas