1、要使用html5,首先要有一个支持html5的浏览器,比如:火狐,谷歌等等,首先在body区域加入一个canvas标签,id为canvas-fram,如一下代码:
<canvas id="canvas-fram"></canvas>
2、在head区域加入一个draw2D函数,在函数内通过document.getElementById("canvas-fram")获得canvas标签对象,然后在通过该对象的getContext("2d")获得可画图形的画板,最后通过fillRect(x,y,width,height)画一个矩形,其中x,y是坐标点,width,height是矩形的宽和高,如一下代码所示:
<script>
function draw2D(){
var canvas=document.getElementById("canvas-fram");
if(canvas==undefined){
return ;
}
var context=canvas.getContext("2d");
context.fillRect(0,0,100,100);
//函数原型为context.fillRect(x,y,widht,height)
//其中x,y坐标位置即图形的左上角位置,width,height表示图形的长和宽,填充颜色默认黑色
}
</script>
3、最后在body添加一个οnlοad="draw2D()",意思是在加载的时候调用此函数,那么完整的代码如下所示:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function draw2D(){
var canvas=document.getElementById("canvas-fram");
if(canvas==undefined){
return ;
}
canvas.width=1000; //设置画布的宽
canvas.height=1000; //设置画布的高
var context=canvas.getContext("2d");
context.fillRect(0,0,100,100);
//函数原型为context.fillRect(x,y,widht,height)
//其中x,y坐标位置即图形的左上角位置,width,height表示图形的长和宽,填充颜色默认黑色
}
</script>
</head>
<body οnlοad="draw2D()">
<canvas id="canvas-fram"></canvas>
</body>
</html>
4、运行效果如下图所示:
5、最后将说明注释到代码中,如下代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function draw2D(){
var canvas=document.getElementById("canvas-fram");
if(canvas==undefined){
return ;
}
canvas.width=1000; //设置画布的宽
canvas.height=1000; //设置画布的高
var context=canvas.getContext("2d");
context.fillRect(0,0,100,100);
//函数原型为context.fillRect(x,y,widht,height)
//其中x,y坐标位置即图形的左上角位置,width,height表示图形的长和宽,填充颜色默认黑色
context.fillStyle="blue"; //设置下一个图形的填充颜色为蓝色
context.fillRect(110,0,100,100); //在坐标为110,0处画一个矩形
context.strokeRect(220,0,100,100); //画一个空心的矩形,就是没有填充颜色,边框默认是灰色的
context.strokeStyle="red"; //将边框的颜色设置为红色
context.strokeRect(330,0,100,100); //画一个边框为红色的矩形
context.fillStyle="rgba(255,0,0,0.5)";//设置颜色为红色,透明度为0.5
context.fillRect(0,110,100,100); //
context.strokeStyle="rgba(0,255,0,0.5)"//设置边框为绿色,透明度为0.5
context.strokeRect(110,110,100,100);
context.clearRect(50,50,100,100);//清除画布上的图形,50,50为坐标,100,100位宽和高
context.beginPath(); //路径的开始,在此注释掉也可以
context.arc(200, 330, 100, 0, Math.PI * 2, true); //画一个半径为100的圆形,此时只保存到显存中,而没有绘制到画布上
context.closePath(); //关闭路径,在此注释掉也可以
context.fillStyle = 'rgba(0,0,255,0.25)'; //设置填充颜色
context.fill(); //将图形绘制到画布上
}
</script>
</head>
<body οnlοad="draw2D()">
<canvas id="canvas-fram"></canvas>
</body>
</html>
最后运行效果如下: