canvas基础讲解篇(一)

相信在工做中你们都会接触到canvas的使用,通常状况下工做中都不会要求画特别可贵图形(用到特别难的图形,大多数选择插件实现)基于此,咱们学会一些常规的操做,而后结合项目进行一些扩展便可知足要求。html

画布

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

<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是成对出现的。markdown

代码实现

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效果是同样的ui

代码实现

// 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 表示是不是逆时针。this

重点说明

画圆或者弧形的时候要注意,若是没有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) -绘制实心文本

重点说明

spa

代码实现

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

后记

若是以为对你有帮助,请点赞或评论,我会更新下去插件

相关文章
相关标签/搜索