HTML5 CANVAS
這個是自己做的練習題
程式碼如下:
<html>
<head>
<meta charset="utf-8">
<title>CANVAS 長條圖</title>
</head>
<body>
<BR>
<BR>
<BR>
<BR>
<BR>
<canvas id="myCanvas" width="600px" height="800px" style="border:1px solid gray" >
您的浏览器不支持 HTML5 canvas 标签。
</canvas>
<script>
var data = [];
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function setdata()
{
data=[];
for(var i = 0;i<10;i++)
{
var rndHeight =parseInt(Math.random()*600);
var rndColor =getRandomColor();
data.push({width:30,height:rndHeight,color:rndColor});
}
}
function genBarChart()
{
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var x=0;
var kind=65;
ctx.clearRect(0, 0, 600, 800);
for(var i =0;i<data.length;i++)
{
ctx.fillStyle=data[i].color;
ctx.fillRect(x,700-data[i].height,30,data[i].height);
ctx.font="30px Arial";
ctx.fillText(String.fromCharCode(kind),x+5,730);
ctx.font="24px Arial";
ctx.fillStyle="black";
ctx.fillText(data[i].height,x,700-data[i].height-5);
x=x+50;
kind=kind+1;
}
}
function executeRun()
{
setdata();
genBarChart();
}
setdata();
genBarChart();
setInterval(executeRun, 2000);
</script>
</body>
</html>