概念
Canvas API提供了一种可以通过JavaScript和HTML的<canvas>元素来绘制图形的方式.
- 它可以用于
动画、游戏画面、数据可视化、图片编辑以及实时视频处理等方面.
Canvas API主要聚焦于2D图形.
- (而同样使用
<canvas>元素的WebGL API则用于绘制硬件加速的2D和3D图形).
使用
demo
<!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>canvas</title>
</head>
<body>
<canvas id="canvas" width="300px" height="300px">
</body>
<script>
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
context[api]();
</script>
</html>
坐标体系
- 在canvas中,坐标原点是左上角.
- x轴向右延伸,y轴向下延伸.
(0,0)
________________\ x
|
|
|
|
|/y
矩形
- 参数:
x:横坐标
y:纵坐标
width:宽
height:高
context.fillRect(x,y,width,height);
context.strokeRect(x,y,width,height);
线条
- 绘制流程:
- 开始绘制路径:
contenxt.Path();.
- 将起点移动到相应位置:
context.moveTo(x,y);.
- 设置一个连接点:
context.lineTo(x,y);.
- 执行实际绘制:
context.stroke();.
contenxt.Path();
context.moveTo(x,y);
context.lineTo(x,y);
context.stroke();
- 闭合绘制流程
- 自动闭合:
context.closePath();.
- 相当于:
context.lineTo(x/** 原点横坐标*/,y/** 原点纵坐标 */);
- 填充闭合路径中的内容:
context.fill();.
context.beginPath();
context.moveTo(x0,y0);
context.lineTo(x1,y1);
context.lineTo(x2,y2);
context.closePath();
context.fill();
context.stroke();
圆弧
- 参数:
x: 横坐标
y: 纵坐标
radius: 半径
startAngle: 圆弧起始角度
endAngle: 圆弧结束角度
anticlockwise: 默认false,是否为逆时针绘制
- 注意:
- 设置角度时,我们通常使用
const angle = v*Math.PI
context.beginPath();
context.arc(100,100,90,0,Math.PI,false);
context.fill();
context.stroken();
文本
- 设置字体:
context.font = '30px arial':
- 字体大小(font-size)
- 字体类型(font-family)
context.font = 'italic 60px serif':
- 字体风格(font-style)
- 字体大小(font-size)
- 字体类型(font-family)
- 相当于
css font
- 绘制文本:
context.fillText(text,x,y):实心文本
context.strokeText(text,x,y):空心文本
样式
- 颜色
- 符合css3标准
context.fillStyle = color: 为轮廓路径设置颜色.
context.fillStyle = 'red'.
context.fillStyle = '#ff0000'.
context.fillStyle = 'rgb(255,0,0)'.
context.fillStyle = 'rgb(255,0,0,1)'.
- 宽度
context.lineWidth = width: 线的宽度.
context.lineWidth = 10.
清除
- 帧:
- 为了实现上一帧向下一帧的转变,我们需要清除上一帧.
- 清除:
context.clearRect(x,y,width,height).
加载图像
const image = new Image();
image.src = 'xxxxx';
image.onload = function () {
context.drawImage(image,x,y,width,height);
}
requestAnimationFrame
- 为解决setTimeout和setInterval中出现的循环间隔60Hz问题.
- 出现了高性能画帧设置: requestAnimationFrame.
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback,1000/30)
}
业务场景
常用库
数据可视化
- apache echarts(apache开源基金会)
- D3.js(与three.js相关)
- antv/G2(蚂蚁金服)
小游戏
什么时候使用canvas?什么时候使用svg?
- 高于一定数量级我们选择使用canvas.
- 低于一定数量级我们选择使用svg.