canvas 是前端的 GDI + 技术,就是一种画图技术。
它本质上就是一个画布,canvas 是一个行内元素。对于低版本浏览器是不支持 canvas 的,那么可以在标签中间写一些友好提示,跟video一样的道理;
下面一个小例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js中 canvas</title> <style> #canvas{ border: 1px solid #000;width:800px;height:600px; } </style> </head> <body> <canvas id="canvas"></canvas> <!-- <div id="2d"></div> --> <script> var canvas =document.getElementById('canvas'); // 创建 2d 画布环境 var ctx = canvas.getContext('2d') ctx.strokeStyle = 'red' // 红色描边 // setLineDash(): 用来绘制虚线,参数是一个数组;5:每段虚线的宽度; 2:每段虚线间的间距 ctx.setLineDash([5, 2]) // x:20; y:20;width:100px;height:100px; ctx.strokeRect(20,20,200,100); </script> </body> </html>
----> canvas 画东西常用的3个 api
1. fillRect:绘制一个填充矩形,默认黑色;
2. strokeRect:绘制一个矩形,默认描边是黑色;
3. clearRect:以矩形的形式来清除一个区域;那么清除完就是一块白。
以上3个的参数都一样: X, Y,W,h
那么可以看出 canvas 只提供了画矩形,你要是想画其他,那就自己画吧!
---> canvas 画线
----> 画弧线
其实就是让线弯曲一定的角度即可;也就是说弯曲多少个弧度
1 弧度公式 : 2π /360= π /180; 表示1角度是多少弧度。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas 画弧线</title>
<style>
#canvas{
border: 1px solid #000;width:800px;height:600px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas =document.getElementById('canvas');
var ctx = canvas.getContext('2d')
// 在80*80的坐标处,画一个50*50的圆
// 50:圆的半径,0:开始的角度, Math.PI*2:结束的角度局,最后一个参数可选,规定应该逆时针还是顺时针绘图。False = 顺时针,true = 逆时针。
ctx.arc(80,80,50,0,Math.PI*2);
ctx.stroke();
</script>
</body>
</html>