用canvas實現一個簡單的畫板

河豚學前端發表於2022-01-02

1.畫板的功能

  • 修改畫筆顏色;
  • 修改畫筆粗細;
  • 橡皮擦;
  • 重置畫板;
  • 撤銷上一步;
  • 儲存成圖片;

    2.所需知識

    Element.getBoundingClientRect() 方法返回元素的大小及其相對於視口的位置。
    ctx.moveTo(x, y) 將一個新的子路徑的起始點移動到(x,y)座標
    ctx.lineTo(x, y) 使用直線連線子路徑的終點到x,y座標

    3.一步步實現

    第一步,實現基本功能,可以畫出來滑鼠路徑;

<canvas id="myCanvas" width="400" height="400"></canvas>

class Board {
  constructor(id) {
    this.canvas = document.getElementById(id);
    this.context = this.canvas.getContext('2d');
    this.isDrawing = false;
    this.posX = 0;
    this.posY = 0;
    this.init();
  }
  init() {
    const bindDown = this.handleMouseDown.bind(this);
    const bindMove = this.handleMouseMove.bind(this);
    this.canvas.addEventListener('mousedown', bindDown);
    this.canvas.addEventListener('mousemove', bindMove);
    window.addEventListener('mouseup', () => {
      this.isDrawing = false;
    });
  }
  handleMouseDown(e) {
    const rect = this.canvas.getBoundingClientRect();
    this.posX = e.clientX - rect.left;
    this.posY = e.clientY - rect.top;
    this.isDrawing = true;
  }
  handleMouseMove(e) {
    if (this.isDrawing === true) {
      const rect = this.canvas.getBoundingClientRect();
      this.drawLine(this.context, this.posX, this.posY,
         e.clientX - rect.left, e.clientY - rect.top);
      this.posX = e.clientX - rect.left;
      this.posY = e.clientY - rect.top;
    }
  }
  drawLine(context, x1, y1, x2, y2) {
    context.beginPath();
    context.strokeStyle = 'black';
    context.lineWidth = 1;
    context.moveTo(x1, y1);
    context.lineTo(x2, y2);
    context.stroke();
    context.closePath();
  }
}
new Board('myCanvas');

第二步,可以修改畫筆顏色;

<input id="colorPicker" type="color" />

document.getElementById('colorPicker').addEventListener('change', e => {
      b.changeColor(e.target.value);
    })
    
    class Board {
        constructor(id, color = '#000') {
              this.penColor = color; 
        }  
        drawLine(context, x1, y1, x2, y2) {
          context.strokeStyle = this.penColor;          
        }
        changeColor(color) {
        this.penColor = color;
      }              
    }

第三步,修改畫筆粗細;

ctx.lineWidth = number;

第四步,橡皮擦;

context.globalCompositeOperation = 'destination-out';
參照刮刮樂功能。

第五步,重置畫板;

context.clearRect(0, 0, width, height);

第六步,撤銷上一步;

this.canvas.toDataURL()
將當前canvas儲存為base64的圖片,存放在陣列中。再設定一個索引,撤銷/恢復修改索引的值,從陣列中取出對應的圖片。

第七步,儲存為圖片;

建立一個a標籤,href為toDataURL()生成的圖片,模擬點選事件,點選a連結。

4.完整程式碼

<div class="opera">
    <input id="colorPicker" type="color" />
    <select id="fontsizeSelect">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
    </select>
    <button id="eraser">橡皮擦</button>
    <button id="reset">重置</button>
    <button id="revoke">撤銷</button>
    <button id="recover">恢復</button>
    <button id="saveAsPic">儲存為圖片</button>
  </div>
  <canvas id="myCanvas" width="400" height="400"></canvas>
 class Board {
      constructor(id, color = '#000', fontsize = 1) {
        this.canvas = document.getElementById(id);
        this.context = this.canvas.getContext('2d');
        this.isDrawing = false;
        this.posX = 0;
        this.posY = 0;
        this.penColor = color;
        this.fontsize = fontsize;
        this.isErasing = false;
        this.step = 0;
        this.histroyList = [];
        this.init();
      }
      init() {
        const bindDown = this.handleMouseDown.bind(this);
        const bindMove = this.handleMouseMove.bind(this);
        this.canvas.addEventListener('mousedown', bindDown);
        this.canvas.addEventListener('mousemove', bindMove);
        window.addEventListener('mouseup', () => {
          this.isDrawing = false;
        });
        this.canvas.addEventListener('mouseup', () => {
          this.step++;
          if (this.step < this.histroyList.length) {
            this.histroyList.length = this.step;
          }
          this.histroyList.push(this.canvas.toDataURL());
        });
        this.histroyList.push(this.canvas.toDataURL());
      }
      handleMouseDown(e) {
        const rect = this.canvas.getBoundingClientRect();
        this.posX = e.clientX - rect.left;
        this.posY = e.clientY - rect.top;
        this.isDrawing = true;
      }
      handleMouseMove(e) {
        const rect = this.canvas.getBoundingClientRect();
        if (this.isErasing) {
          this.context.globalCompositeOperation = 'destination-out';
          this.context.beginPath();
          this.context.arc(e.clientX - rect.left, e.clientY - rect.top,
             10, 0, Math.PI * 2);
          this.context.fill();
        } else if (this.isDrawing === true) {
          this.drawLine(this.context, this.posX, this.posY,
         e.clientX - rect.left, e.clientY - rect.top);
          this.posX = e.clientX - rect.left;
          this.posY = e.clientY - rect.top;
        }
      }
      drawLine(context, x1, y1, x2, y2) {
        context.beginPath();
        context.strokeStyle = this.penColor;
        context.lineWidth = this.fontsize;
        context.moveTo(x1, y1);
        context.lineTo(x2, y2);
        context.stroke();
        context.closePath();
      }
      changeColor(color) {
        this.penColor = color;
      }
      changeFontSize(size) {
        this.fontsize = size;
      }
      switchEraseStatus() {
        this.isErasing = !this.isErasing;
      }
      clearBoard() {
        this.context.clearRect(0, 0, window.myCanvas.width,
     window.myCanvas.height);
        this.step = 0;
        this.histroyList = [];
      }
      revoke() {
        if (this.step > 0) {
          this.step--;
          this.context.clearRect(0, 0, window.myCanvas.width, 
        window.myCanvas.height);
          let pic = new Image();
          pic.src = this.histroyList[this.step];
          pic.addEventListener('load', () => {
            this.context.drawImage(pic, 0, 0);
          })
        } else {
          console.log('不能繼續撤銷了')
        }
      }
      recover() {
        if (this.step < this.histroyList.length - 1) {
          this.step++;
          this.context.clearRect(0, 0, window.myCanvas.width,
       window.myCanvas.height);
          let pic = new Image();
          pic.src = this.histroyList[this.step];
          pic.addEventListener('load', () => {
            this.context.drawImage(pic, 0, 0);
          })
        } else {
          console.log('不能繼續恢復了')
        }
      }
      saveAsPic() {
        const el = document.createElement('a');
        el.href = this.canvas.toDataURL();
        el.download = 'canvas';
        const event = new MouseEvent('click');
        el.dispatchEvent(event);
      }
    }
    const b = new Board('myCanvas');


    window.colorPicker.addEventListener('change', e => {
      b.changeColor(e.target.value);
    })


    window.fontsizeSelect.addEventListener('change', e => {
      b.changeFontSize(window.fontsizeSelect.value);
    })


    window.eraser.addEventListener('click', () => {
      b.switchEraseStatus();
    })


    window.reset.addEventListener('click', () => {
      b.clearBoard();
    })


    window.revoke.addEventListener('click', () => {
      b.revoke();
    })


    window.recover.addEventListener('click', () => {
      b.recover();
    })


    window.saveAsPic.addEventListener('click', () => {
      b.saveAsPic();
    })

相關文章