我在畫布中做了一個簡單的圖形,但在解決兩個問題時遇到了困難。畫布圖形錯誤地繪製數據
第一個問題是自動爲垂直軸設置適當的比例,併爲陣列中的每個數據值留出足夠的空間。理想情況下,我希望這些數字可以根據實際值範圍更接近於百萬或千等,而不是像33145
這樣的值作爲第一條比例線。
當前一個值對於比例太高而且不在畫布上繪製,因爲它超出範圍。
第二個問題是,點似乎並沒有在他們的正確位置上繪圖,我不確定我的錯誤在哪裏。
我做了一個的jsfiddle因爲在大多數情況下它可能是一個有點混亂,沒有看到它在行動:
這是我繪製我的數據並得出我的縱軸:
垂直軸:
var x = 0,
y,
range = data.max() - data.min(),
valueStep = range/10,
// get width of largest number
margin = 3 + ctx.measureText(data.min() + (valueStep*10)).width,
pixelStep = (graph.height-40)/10,
verticalP = pixelStep,
output;
// draw left hand values
for(var i = 0; i < 11; i++){
output = data.min() + (valueStep*i);
y = graph.height-20 - (verticalP + i*pixelStep);
ctx.fillText(output,x,y+6);
ctx.beginPath();
ctx.moveTo(margin, y);
ctx.lineTo(x2,y);
ctx.stroke();
}
個數據繪圖:
var y = graph.height,
x = margin,
pos,
valueStep = (graph.width-(margin*2))/data.length,
pixelRange = graph.height-20,
pp = range/pixelRange;
for(var i = 0; i < data.length; i++){
x += valueStep;
pos = x - (valueStep/2);
ctx.beginPath();
ctx.moveTo(x, graph.height-20);
ctx.lineTo(x, graph.height);
ctx.stroke();
ctx.fillText('Week '+(i+1),pos-(ctx.measureText('Week '+(i+1)).width/2),y);
ctx.beginPath();
ctx.arc(pos,(graph.height-20)-(verticalP+(data[i]/pp)),2,0,2*Math.PI);
ctx.stroke();
ctx.fill();
}
下面是一個SO問答展示瞭如何在畫布中保留值:http://stackoverflow.com/questions/22638453/dynamic-scaling-for-canvas-graphs/22644216#22644216 – markE
感謝您的支持!我將把它合併到一起,使它在未來更容易! – Sir