Anthony Chao

JS30 day8 Fun With HTML5 Canvas

#Javascript

JS30 day08 - Fun With HTML5 Canvas

作業內容

今天要做出一個網頁,可以在上面畫畫,隨著畫筆移動,顏色會一直循環,色筆粗度也會變大變小 可以參考這份 CodePen

學到什麼

  • HTML

    1. canvas 這個 HTML 標籤就是用來使用 JS 畫圖的
  • JS

    1. 在canvas 上面用 JS 畫畫的時候,並不是直接畫在 html 的 canvas 上面,而是畫在 context(渲染環境) 上面,一個畫布可以同時有好幾個渲染環境,環境必須指定他是 2D 或是 3D
    const canvas = document.querySelector('#draw');
    const ctx = canvas.getContext('2d');

    MDN: https://developer.mozilla.org/zh-TW/docs/Web/API/Canvas_API/Tutorial/Basic_usage

    1. 全域變數 window 的 innerHeight/innerWidth 就代表當下螢幕畫面寬/高 canvas.width = window.innerWidth;

    2. canvas 的 context 相關方法跟屬性真的多到記不起來,不過以後用到的機會應該也不多,所以就先把這次用到的先記錄下來:

    //屬性
    ctx.strokeStyle = '#BADA55'; //畫筆的顏色
    ctx.lineJoin = 'round'; //兩條線交會的時候是圓形
    ctx.lineCap = 'round'; //線的起終點是圓形
    ctx.lineWidth = 50; //筆的寬度
    
    //方法
    ctx.beginPath(); //產生一個新路徑,路徑會被存在一個次路徑 (sub-path) 清單中
    ctx.moveTo(lastX, lastY); //設定畫圖起點
    ctx.lineTo(e.offsetX, e.offsetY); //lineTo是畫直線的時候表示要到哪裡,其他還有畫各種曲線的方法
    ctx.stroke(); //畫出圖形邊框
    1. 如果想要用動畫配合顏色變化,顏色可以用 hsl 表示,因為他的第一個值可以從 0~360 一直循環 https://mothereffinghsl.com/

    2. mouseout 這個 event 用在滑鼠離開指定 selector 時觸發

總結

雖然之後可能會用到這個的機會很少,但我覺得這個練習對於事件的控制來說還滿有幫助的!

參考資料: https://github.com/wesbos/JavaScript30

code 內容: JS:

const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

ctx.strokeStyle = '#BADA55';
ctx.lineJoin = 'round'
ctx.lineCap = 'round'
ctx.lineWidth = 50;

let isDrawing = false;
let lastX = 0;
let lastY = 0;
let hue = 0;
let direction = true;

function draw(e){
  if(!isDrawing) return; // 滑鼠沒按著就不跑這 function
  ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`
  ctx.beginPath();
  ctx.moveTo(lastX, lastY);
  ctx.lineTo(e.offsetX, e.offsetY);
  ctx.stroke();
  [lastX, lastY] = [e.offSetX, e.offSetY];
  hue++;
  if(hue >= 360){
    hue = 0;
  }
  if(ctx.lineWidth >= 100 || ctx.lineWidth <= 1){
    direction = !direction;
  }
  if(direction){
    ctx.lineWidth++;
  } else {
    ctx.lineWidth--;
  }
}

canvas.addEventListener('mousemove', draw)
canvas.addEventListener('mousedown', function(e){
  isDrawing = true;
  [lastX, lastY] = [e.offSetX, e.offSetY];
})
canvas.addEventListener('mouseup', function(){ isDrawing = false })
canvas.addEventListener('mouseout', function(){ isDrawing = false })