Canvas是HTML5新增的组建,它就像一块幕布,可以用JavaScript在上面绘制各种图标、动画等。
一、测试浏览器是否支持canvas
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>canvas绘图</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js"></script>
</head>
<body>
<canvas id="test-canvas" width="300" height="200">
<p>您的浏览器不支持Canvas</p>
</canvas>
<script type="text/javascript">
let canvas = document.getElementById('test-canvas');
// 测试浏览器是否支持canvas
if (canvas.getContext) {
console.log('你的浏览器支持canvas');
} else {
console.log('你的浏览器不支持canvas');
}
</script>
</body>
</html>
二、canvas绘图
1、绘制形状(笑脸)
<script type="text/javascript">
'use strict';
let canvas = document.getElementById('test-canvas');
// 测试浏览器是否支持canvas
if (canvas.getContext) {
console.log('你的浏览器支持canvas');
// 绘制笑脸
this.painting(canvas);
} else {
console.log('你的浏览器不支持canvas');
}
function painting(canvas) {
// 得到一个CanvasRenderingContext2D对象
let ctx = canvas.getContext('2d');
// 将(0, 0)位置大小为200*200的矩形变透明
ctx.clearRect(0, 0, 200, 200);
ctx.fillStyle = '#dddddd'; // 设置颜色
ctx.fillRect(10, 10, 130, 130); // 把(10, 10)位置大小为130*130的矩形涂色
// 利用Path绘制复杂路径
let path = new Path2D();
path.arc(75, 75, 50, 0, Math.PI*2, true);
path.moveTo(110, 75);
path.arc(75, 75, 35, 0, Math.PI, false);
path.moveTo(65, 65);
path.arc(60, 65, 5, 0, Math.PI*2, true);
path.moveTo(95, 65);
path.arc(90, 65, 5, 0, Math.PI*2, true);
ctx.strokeStyle = '#0000ff';
ctx.stroke(path);
}
</script>
代码输出结果: