前端analysis | 3w & 1h

《canvas》- canvas doc 学习笔记之绘线

2020-04-20

介绍

canvas vs svg

  • canvas 适用于动态创建的位图,缩放失真。
  • svg 适用于静态描述的矢量图,缩放不失真。
  • canvas 基于”状态”绘制图形,譬如,strokeStyle、fillStyle、lineWidth等
  • svg基于dom,可以直接在html中展示

绘图四步骤

  • 定义canvas,设置width,height属性,设置变形等特效
  • 获取canvas 2D context,绘制图形
  • 添加动画
  • 添加交互

canvas w3c坐标系

canvas width\height设置

1
2
3
const dom = document.getElementById('canvas');
dom.width = window.innerWidth;
dom.height = window.innerHeight;
1
<canvas id="canvas" width="600" height="700"></canvas>

canvas 绘直线

线段,只能用stroke

  • 单条描边
    1
    2
    3
    4
    5
    6
    7
    ctx.moveTo(30,40);
    ctx.lineTo(130,140);
    # 线条宽度,默认1px
    ctx.lineWidth = 10;
    ctx.lineHeight = '10'
    #绘制边
    ctx.stroke();
  • 多条
    1
    2
    3
    4
    5
    6
    7
    ctx.moveTo(0,0);
    ctx.lineCap = "round"
    ctx.lineTo(300,100);
    ctx.lineTo(400,50);
    ctx.lineWidth = 12;
    ctx.lineJoin = 'round' //mitter 默认,round圆角,bevel 斜角
    ctx.stroke();

    矩形

  • 利用绘制多条边特点
    1
    2
    3
    4
    5
    6
    7
    8
    ctx.moveTo(100,100);
    ctx.lineTo(300,100);
    ctx.lineTo(300,200);
    ctx.lineTo(100,200);
    ctx.lineTo(100,100);
    ctx.strokeStyle= 'blue';
    ctx.setLineDash([10,30]); //10px实线,30px 虚线
    ctx.stroke();
  • 绘制描边矩形
    1
    2
    3
    4
    5
    6
    7
    ctx.strokeStyle= 'blue';
    ctx.strokeRect(100,210,200,100);

    # or
    ctx.strokeStyle= 'blue';
    ctx.rect(100,320,200,100);
    ctx.stroke();
  • 绘制填充矩形
    1
    2
    3
    4
    5
    6
    7
    ctx.fillStyle = 'red';
    ctx.fillRect(100,430,200,100);

    ctx.fillStyle = 'green'
    ctx.rect(100,540,200,100);
    ctx.fill();

  • 清空矩形
    1
    2
    3
    ctx.fillStyle = 'red';
    ctx.fillRect(100,430,200,100);
    ctx.clearRect(120,450,100,50);

  • 定义如何绘制
    1
    ctx.arc(50,50,40,0,135*Math.PI/180,true);
  • 绘制描边圆
    1
    2
    3
    ctx.arc(50,50,40,0,135*Math.PI/180,true);
    ctx.strokeStyle = 'red'
    ctx.stroke();
  • 绘制填充圆
    1
    2
    3
    4
    5
    ctx.beginPath();
    ctx.arc(250,50,40,0,135*Math.PI/180,true);
    ctx.closePath();
    ctx.fillStyle = 'blue';
    ctx.fill();
  • 路径闭合
    1
    2
    3
    4
    5
    6
    ctx.beginPath();
    ctx.arc(50,50,40,0,135*Math.PI/180,true);
    ctx.closePath();
    #先定义闭合,在绘制
    ctx.strokeStyle = 'red'
    ctx.stroke();

弧线

  • arc 描边
    1
    2
    3
    ctx.arc(50,50,40,0,40*Math.PI/180,true);
    ctx.strokeStyle = 'red'
    ctx.stroke();
  • arcTo
    1
    2
    3
    # 150,50 为结束点,120,180为终点,20为半径,绘制圆弧
    ctx.arcTo(150,50,120,180,20);
    ctx.stroke();
Tags: anvas
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏