1 canvas基本api
HTML
<canvas id="canvas" width="800" height="600"></canvas>
JS
const canvas = document.getElementById("canvas"); // 获取画布
const ctx = canvas.getContext("2d"); // 获取2d画布环境
ctx.beginPath(); // 开始
ctx.moveTo(0, 0); // 画笔指定开始点
ctx.lineTo(10,10); // 连接当前端点和指定的坐标点
ctx.font = '16px SimHei'; // 字体
ctx.lineWidth = 1; // 设置线宽
ctx.strokeStyle = "red"; // 设置线的颜色
ctx.stroke(); // 沿着绘制路径的坐标点顺序绘制直线
2 canvas画图计算
这次要画一个折线图需要计算的有:坐标轴,点(x,y)
首先计算坐标轴
// 假设这是我们获取的数据
const arr = [
{
key: '1月', mount: 100},
{
key: '2月', mount: 200},
{
key: '3月', mount: 250},
{
key: '4月', mount: 110},
{
key: '5月', mount: 500},
{
key: '6月', mount: 600},
];
// 获取画布的高宽
const cw = canvas.width;
const ch = canvas.height;
// 内边居
const padding = 80;
//原点,x终点,y终点
const origin = {
x: padding, y: ch - padding};
const xAisa = {
x: cw - padding, y: ch - padding};
const yAisa = {
x