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

後記

若是以爲對你有幫助,請點贊或評論,我會更新下去插件

相關文章
相關標籤/搜索