是HTML5中新增的标签,用于绘制图形,这个标签和其他的标签一样,其特殊之处在于该标签可以获取一个CanvasRenderingContext2D对象,我们可以通过JavaScript脚本来控制该对象进行绘图。
只是一个绘制图形的容器,除了id、class、style等属性外,还有height和width属性。在>元素上绘图主要有三步:
获取元素对应的DOM对象,这是一个Canvas对象;
调用Canvas对象的getContext()方法,得到一个CanvasRenderingContext2D对象;
调用CanvasRenderingContext2D对象进行绘图。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas绘图演示</title>
<style type="text/css">
#canvas{
border: 1px solid #ADACB0;
display: block;
margin: 20px auto;
}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="300">
你的浏览器还不支持canvas
</canvas>
</body>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//设置对象起始点和终点
context.moveTo(10,10);
context.lineTo(200,200);
//设置样式
context.lineWidth = 2;
context.strokeStyle = "#F5270B";
//绘制
context.stroke();
</script>
</html>
如果没有通过moveTo()特别指定,lineTo()的起始点是以上一个点为准。因此,如果需要重新选择起始点,则需要通过moveTo()方法。如果需要对不同的线段设置样式,则需要通过context.beginPath()重新开启一条路径
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//设置对象起始点和终点
context.beginPath();
context.moveTo(100,100);
context.lineTo(700,100);
context.lineTo(700,400);
context.lineWidth = 2;
context.strokeStyle = "#F5270B";
//绘制
context.stroke();
context.beginPath();
context.moveTo(100,200);//这里的moveTo换成lineTo效果是一样的
context.lineTo(600,200);
context.lineTo(600,400);
//strokeStyle的颜色有新的值,则覆盖上面设置的值
//lineWidth没有新的值,则按上面设置的值显示
context.strokeStyle = "#0D25F6";
//绘制
context.stroke();
</script>
绘制矩形rect()、fillRect()和strokeRect()
context.rect( x , y , 宽 高)
context.fillRect( x , y ,宽 高)
context.strokeRect( x , y ,宽 高 )
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//使用rect方法
context.rect(10,10,190,190);
context.lineWidth = 2;
context.fillStyle = "#3EE4CB";
context.strokeStyle = "#F5270B";
context.fill();
context.stroke();
//使用fillRect方法
context.fillStyle = "#1424DE";
context.fillRect(210,10,190,190);
//使用strokeRect方法
context.strokeStyle = "#F5270B";
context.strokeRect(410,10,190,190);
//同时使用strokeRect方法和fillRect方法
context.fillStyle = "#1424DE";
context.strokeStyle = "#F5270B";
context.strokeRect(610,10,190,190);
context.fillRect(610,10,190,190);
</script>
**注意!!!!**stroke()和fill()绘制的前后顺序,如果fill()后面绘制,那么当stroke边框较大时,会明显的把stroke()绘制出的边框遮住一半