在使用Canvas绘制柱形图时,我对xScale和yScale有疑问,这里是代码:
<html>
<head>
<title>Bar Graph</title>
<style>#canvas{background: #ffffff;
box-shadow:5px 5px 5px #ccc;
border:5px solid #eee;
margin-bottom:10px;}</style>
<script type="text/javascript">
var canvas ;
var context ;
var Val_Max;
var Val_Min;
var sections;
var xScale;
var yScale;
var y;
// values of each item on the graph
var itemName = [ "Red", "Blue", "Green"];
var itemValue = [ 12144,12179, 12144 ];
function init() {
// intialize values for each variables
sections = 3;
Val_Max = 13000;
var stepSize = 1000;
var columnSize = 50;
var rowSize = 60;
var margin = 10;
var header = "Counts"
//
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
context.fillStyle = "#000000;"
yScale = (canvas.height - columnSize - margin)/ 13000 ;
xScale = (canvas.width - rowSize) / (sections+1);
context.strokeStyle="#000;"; // background black lines
context.beginPath();
// column names
context.font = "19 pt Arial;"
context.fillText(header, 0, columnSize-margin*2);
// draw lines in the background
context.font = "16 pt Helvetica"
var count = 0;
for (scale=Val_Max;scale>=0;scale = scale - stepSize) {
y = columnSize + (yScale * count * stepSize);
context.fillText(scale, margin, y);
context.moveTo(rowSize,y)
context.lineTo(canvas.width,y)
count++;
}
context.stroke();
// print names of each data entry
context.font = "20 pt Verdana";
context.textBaseline="bottom";
function computeHeight(value) {
y = canvas.height - value * yScale ;
}
for (i=0;i<4;i++) {
computeHeight(itemValue[i]);
context.fillText(itemName[i], xScale * (i+1), y-margin) ;
}
// shadow for graph's bar lines with color and offset
context.fillStyle="#9933FF;";
context.shadowColor = 'rgba(128,128,128, 0.5)';
//shadow offset along X and Y direction
context.shadowOffsetX = 9;
context.shadowOffsetY = 3;
// translate to bottom of graph in order to match the data
context.translate(0,canvas.height - margin);
context.scale(xScale, -1*yScale);
// draw each graph bars
for (i=0;i<4;i++) {
context.fillRect(i+1, 0, 0.3, itemValue[i]);
}
}
</script>
</head>
<body onLoad="init()">
<div>
<h2>Pixel Value by colour</h2>
<canvas id="canvas" height="400" width="650">
</canvas>
</div>
</body>
</html>
我不确定xScale和yScale在柱形图中的含义是什么,我试图对它们进行一些修改以查看图形的样子,但仍然没有得到平均值,请指教,谢谢。
答案 0 :(得分:0)
xScale&amp; yScale变量以两种方式使用。
xScale&amp; amp;的第一个目的yScale:强>
它们用于使您的图表适合画布中可用的现有空间。
例如,如果您将画布宽度更改为450,您将看到图表会自动缩小条形和宽度。间距适合较小的水平空间。这是通过xScale&amp; amp;中使用的计算完成的。 yScale。
// The bars & spacing of the chart are narrower
// because of the xScale & yScale calculations
<canvas id="canvas" height="400" width="650">
xScale&amp; amp;的第二个目的yScale:强>
图表通常在图表底部有y = 0坐标。
然而,在html画布中,y = 0坐标位于画布的顶部
此行有效地从上到下翻转画布的normail y = 0:
context.scale(xScale, -1*yScale);
插图:
当画布为400 x 650时,这是您的图表:
<canvas id="canvas" width=500 height=300></canvas>
当画布为500 x 300时,这是您的图表:
除了调整画布元素
之外,没有进行任何代码更改<canvas id="canvas" width=500 height=300></canvas>