前端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>

路径状态

路径beginPath

  • beginPath 开启新的路径

  • 没有beginPath,后面出现的相同的配置值,重复叠加设置,但不会替换

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    ctx.moveTo(100,100);
    ctx.lineTo(250,100);
    ctx.strokeStyle= 'rgba(255,0,0,.3)';
    ctx.stroke();

    ctx.moveTo(200,150);
    ctx.lineTo(350,150);
    ctx.strokeStyle= 'rgba(255,0,0,.3)';
    ctx.stroke();

    ctx.moveTo(250,200);
    ctx.lineTo(350,200);
    ctx.strokeStyle= 'rgba(255,0,0,.4)';
    ctx.stroke();
  • beginPath、closePath、isPointPath

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    ctx.moveTo(100,100);
    ctx.lineTo(250,100);
    ctx.strokeStyle= 'red';
    ctx.stroke();

    ctx.beginPath();
    ctx.moveTo(200,150);
    ctx.lineTo(350,150);
    ctx.strokeStyle= 'green';
    ctx.stroke();

    ctx.beginPath();
    ctx.moveTo(250,200);
    ctx.lineTo(350,200);
    ctx.strokeStyle= 'blue';
    ctx.stroke();
  • closePath()主要用于实现“封闭图形”,例如三角形、多边形、圆形、扇形等

  • clip裁剪 - 改变基础图形,具备裁剪能力
    Canvas两个方法:strokeRect()、fillRect()绘制的图形,clip()不支持

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    ctx.beginPath();
    ctx.strokeStyle= 'red';
    ctx.arc(50,50,40,0,360*Math.PI/180,false);
    ctx.stroke();
    ctx.clip();

    ctx.beginPath();
    ctx.fillStyle = '#66ccff';
    ctx.rect(50,50,200,100);
    ctx.fill();

状态save和restore

  • 图形或图片裁切。
  • 图形或图片变形。
  • 以下属性改变的时候:fillStyle、font、globalAlpha、globalCompositeOperation、lineCap、lineJoin、lineWidth、miterLimit、shadowBlur、shadowColor、shadowOffsetX、shadowOffsetY、strokeStyle、textAlign、textBaseline。
    • 填充效果:fillStyle。
    • 描边效果:strokeStyle。
    • 线条效果:lineCap、lineJoin、lineWidth、miterLimit。
    • 文本效果:font、textAlign、textBaseline。
    • 阴影效果:shadowBlur、shadowColor、shadowOffsetX、shadowOffsetY。
    • 全局属性:globalAlpha、globalCompositeOperation。
Tags: canvas
使用支付宝打赏
使用微信打赏

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