画布
canvas元素是H5中新增的一个重要元素,专门用来绘制图形。在页面中放置一个canvas元素,就相当于在页面上放置一块画布,可以利用canvas api在其中进行图形的描绘。
一、canvas的方法?
样式设置及绘制:fillStyle、strokeStyle、fill()、stroke()
渐变样式: createLinearGradient()、 createRadialGradient()
绘制矩形:fillRect()、strokeRect()
绘制路径:beginPath()、arc()、moveTo()、lineto()、 bezierCurveTo
()、closePath()
坐标变换:translate()、scale()、rotate()
绘制图像:drawImage()
绘制文本:fillText()
二、简单使用
代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>画布</title>
<style>
canvas {
border: 1px solid #333;
}
</style>
</head>
<body>
<canvas id="app" width="500" height="500"></canvas>
</body>
<script>
window.onload = function() {
// 1.获取画布节点对象
var canvas = document.querySelector('#app');
// 2.获取画布的上下文对象(画笔)
var context = canvas.getContext('2d');
// 3.开始路径
context.beginPath();
// 4.设置圆的配置参数
// 表示弧度 Math.PI 180对应的弧度
// 参数表示 x,y,r,开始弧度,结束弧度
context.arc(200,200,100,0,Math.PI,true)
// 绘制直线
context.lineTo(200,200);
// 闭合路径
context.closePath();
// 执行绘制
context.fillStyle = 'teal';
context.strokeStyle = 'teal';
context.fill();
context.stroke();
}
</script>
</html>
具体案例——笑脸
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>笑脸</title>
<style>
canvas {
border: 1px solid #333;
}
</style>
</head>
<body>
<canvas id="app" width="500" height="500"></canvas>
</body>
<script>
window.onload = function() {
// 1.获取画布节点对象
var canvas = document.querySelector('#app');
// 2.获取画布的上下文对象(画笔)
var context = canvas.getContext('2d');
// 3.开始路径
context.beginPath();
context.arc(200,200,100,0,Math.PI*2,true)
context.fillStyle = 'yellow';
context.strokeStyle = 'black';
context.fill();
context.stroke();
//左眼
context.beginPath();
context.arc(150,180,20,0,Math.PI*2,true)
context.fillStyle = 'white';
context.strokeStyle = 'black';
context.fill();
context.stroke();
//右眼
context.beginPath();
context.arc(250,180,20,0,Math.PI*2,true)
context.fillStyle = 'white';
context.strokeStyle = 'black';
context.fill();
context.stroke();
//左眼珠
context.beginPath();
context.arc(150,180,10,0,Math.PI*2,true)
context.fillStyle = 'black';
context.strokeStyle = 'black';
context.fill();
context.stroke();
//右眼珠
context.beginPath();
context.arc(250,180,10,0,Math.PI*2,true)
context.fillStyle = 'black';
context.strokeStyle = 'black';
context.fill();
context.stroke();
context.beginPath();
context.arc(200,200,60,57,Math.PI*10/12,false)
context.fillStyle = 'teal';
context.strokeStyle = 'black';
context.stroke();
}
</script>
</html>