canvas基础讲解篇(一)

718 阅读2分钟

相信在工作中大家都会接触到canvas的使用,一般情况下工作中都不会要求画特别难得图形(用到特别难的图形,大多数选择插件实现)基于此,我们学会一些常规的操作,然后结合项目进行一些扩展即可满足要求。

画布

canvas的画布是一个H5新增的标签。

 <canvas id="canvas" width="1000" height="600" style="background-color: aliceblue;">您的浏览器不支持canvas</canvas>

canvas主要通过js画图,接下来我们详细讲讲怎么画一些图形。

  class Draw {
      constructor(ctx) {
          this.ctx = ctx;
      }
      // 画图方法
      // ...
  }
  window.onload = function() {
    const canvas = document.querySelector('#canvas');
    const ctx = canvas.getContext('2d');
    const draw = new Draw(ctx);
    // 一些画图操作
    // ...
  }

绘制线段

API讲解

  • ctx.moveTo(x, y) -设置画线起点
  • ctx.lineTo(x, y) -设置画线终点
  • ctx.linewidth - 设置线的宽度
  • ctx.strokeStyle - 设置轮廓的颜色
  • ctx.stroke() -填充轮廓

重点说明

strokeStyle和stroke是成对出现的。

代码实现

drawLine() {
  this.ctx.moveTo(10,10); // 开始位置
  this.ctx.lineTo(50, 10);
  this.ctx.lineWidth = 5;
  this.ctx.strokeStyle = 'red';
  this.ctx.stroke();
 }

效果截图

image.png


绘制矩形

API讲解

  • ctx.rect(x, y, width, height) -绘制矩形路径
  • ctx.strokeRect(x, y, width, height) - 绘制矩形
  • ctx.fillRect(x, y, width, height) -绘制填充矩形
  • ctx.clearRect(x, y, width, height) -清除矩形区域

重点说明

rect和strokeRect效果是一样的

代码实现

 // rect
   drawRect() {
      this.ctx.strokeStyle = 'red';
      this.ctx.strokeRect(10, 50, 40, 20);

      this.ctx.fillStyle = 'red';
      this.ctx.fillRect(60, 50, 40, 20);
    }

效果截图

image.png


绘制圆形

API讲解

  • ctx.arc(x,y,radius,start,end,anticlockwise) - 绘制圆形或扇形 上述的参数中,x,y 表示圆心的坐标,radius 是半径,start 开始弧度,end 结束弧度,anticlockwise 表示是否是逆时针。

重点说明

画圆或者弧形的时候要注意,如果没有beginPath,将会以画布的最左侧为起始点,图形如下

image.png

代码实现

    // arc
    drawArc() {
      this.ctx.beginPath();
      this.ctx.arc(100, 150, 50, Math.PI * 2, false);
      this.ctx.closePath();
      this.ctx.lineWidth = 5;
      this.ctx.strokeStyle = 'red';
      this.ctx.stroke();
      this.ctx.fillStyle = 'green',
      this.ctx.fill();
    }

效果截图

image.png

绘制文本

API讲解

  • strokeText(string, x, y) -绘制空心文本
  • fillText(string, x, y) -绘制实心文本

重点说明

代码实现

drawText() {
      this.ctx.fillStyle = 'red';
      this.ctx.font = 'bold 40px 微软雅黑';
      this.ctx.fillText('实心文本', 150, 200);

      this.ctx.strokeStyle = 'green';
      this.ctx.font = 'bold 40px 微软雅黑';
      this.ctx.lineWidth = 1;
      this.ctx.strokeText('空心文本', 150, 250)
    }

效果截图

image.png

后记

如果觉得对你有帮助,请点赞或评论,我会更新下去