html5基础教程:Canvas元素应用画数据图型1
在html5的Canvas元素最流行的应用当属绘制图形数据。在这部分中,我们将开始对如何在Canvas上绘制图形数据做一个很简单的例子。 然后我们就可以建立在这些基本概念,使我们的图形功能更灵活。你可以复制下面代码来查看运行时的效果。
<section>
<div>
<canvas id="canvas" width="180" height="105">
This text is displayed if your browser
does not support HTML5 Canvas.
</canvas>
</div>
<script type="text/javascript">
var canvas;
var ctx;
var j;
var x = 0;
var y = 105;
var WIDTH = 180;
var HEIGHT = 105;
var temps = [15,30,10,13,27,30,14];
function drawaxes(){
ctx.strokeStyle = "black";
/* y axis along the left edge of the canvas*/
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(0,105);
ctx.stroke();
/* x axis along the bottom edge of the canvas*/
ctx.moveTo(0,105);
ctx.lineTo(180,105);
ctx.stroke();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
draw();
}
function plotdata(){
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.moveTo(0,HEIGHT-(temps[0]));
j = 1;
for (var i in temps){
ctx.lineTo(j*30,HEIGHT-(temps[j]));
ctx.stroke();
j++;
}
}
function draw() {
clear();
drawaxes();
plotdata();
}
init();
</script>
</section>
下面是我制作的图形数据,他是一周的气温
| 天 | 气温 |
| 1 | 15 |
| 2 | 30 |
| 3 | 10 |
| 4 | 13 |
| 5 | 27 |
| 6 | 30 |
| 7 | 14 |
创建一个2D Canvas上下文
绘制X轴
绘制Y轴
根据数据绘制路径
我们需要了解如何绘制到画布元素的点。 在X轴从0开始从左边增加,当你移动到右边,y轴从0开始的顶部,并增加你下移。

在网页中定义一个
<canvas id="canvas" width="180" height="105">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
使用javascript获取
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
draw();
}
首先我们获取了canvas 的element ID,然后我们得到了一个在我们的画布让我们用它做的东西在JavaScript中的表单对象。这个上下文包含绘图画布,如对基本方法arc(),lineto()、stroke().下面我们将调用draw()函数来绘制图形。
function draw() { clear(); drawaxes(); plotdata(); }使用clear()函数清除多有大小相同的矩形,function clear() { ctx.clearRect(0, 0, WIDTH, HEIGHT); }使用我们的drawaxes()函数绘制X/Y轴function drawaxes(){ ctx.strokeStyle = "black"; ctx.beginPath(); /* y axis along the left edge of the canvas*/ ctx.moveTo(0,0); ctx.lineTo(0,105); ctx.stroke(); /* x axis along the bottom edge of the canvas*/ ctx.moveTo(0,105); ctx.lineTo(180,105); ctx.stroke(); }对于上下文strokestyle设置为我们想要的颜色风格的方法,当我们使用它来绘制我们的路径。
效果如图

好啦,第一部分就介绍到这里。在下一部分中我将在美化图形数据。

