我目前正在尝试创建的是一个可视化一些数据的坐标系。我不想使用现有的框架,但想从头开始创建它。
我所拥有的是三点,例如 (15, 20), (-5,1), (120,-17)。他们用 x-min = -5 和 x-max = 120 和 y-min = -17 和 x-max = 20 定义坐标系的比例。这个比例是我无法找到的,因为它应该是有意义的。在此示例中,让坐标系从 (-100, -100) 到 (100,100) 每 10 个标记一个标记是没有意义的。
<html>
<head>
<script type="text/javascript">
function drawShape(){
var canvas = document.getElementById('mycanvas');
if (canvas.getContext){
//draw canvas
var context = canvas.getContext('2d');
var canvasBorder = Math.floor(canvas.scrollHeight * 0.1);
var xLength = Math.floor(canvas.scrollWidth - (canvasBorder * 2));
var yLength = Math.floor(canvas.scrollHeight - (canvasBorder * 2));
//draw coordinate system
context.beginPath();
context.moveTo(canvasBorder, canvasBorder); //30,30
context.lineTo(canvasBorder, canvasBorder + yLength); //30,270
context.lineTo(canvasBorder + xLength, canvasBorder + yLength); //370,30
context.stroke();
//easy: define 5 values for x-axis
var xMaxValue = 5;
var tmp = Math.floor(xLength / xMaxValue);
for(i = 0; i <= xMaxValue; i++){
context.beginPath();
context.moveTo(canvasBorder + tmp*i, canvasBorder + yLength);
context.lineTo(canvasBorder + tmp*i, canvasBorder + yLength+10);
context.fillText(i, canvasBorder + tmp*i, canvasBorder + yLength+10);
context.stroke();
}
//difficult: have a max value for y-axis
//too much space between 117 and 200, should display 120 or 150 instead
//next level, what happens with -20 instead of 0 for min-y
var yMaxValue = 117;
var yIncrement = Math.pow(10, (Math.abs(Math.floor(yMaxValue)).toString().length)) / 10;
var topValue = Math.floor(yMaxValue / yIncrement) + 1;
var tmp = parseInt(yLength / topValue);
for(i = 0; i <= topValue; i++){
context.beginPath();
context.moveTo(canvasBorder, yLength + canvasBorder - tmp*i);
context.lineTo(canvasBorder - 10, yLength + canvasBorder - tmp*i);
context.fillText(yIncrement * i, canvasBorder - 10, yLength + canvasBorder - tmp*i);
context.stroke();
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body onload="drawShape();">
<canvas id="mycanvas" width="400" height="300"
style="border:1px solid #ddd;">
</canvas>
</body>
</html>
还是有更好的方法来获取数据以相应地创建坐标系?
干杯,弗洛里安