Draw on Image using canvas

let initCanvas = function(){
    // Canvas DOM 元素
    let canvas = document.getElementById('canvas_cxr')
    let ctx = canvas.getContext('2d')

    // 使用中的圖
    var img = $targetImg ? $targetImg.get(0) : document.getElementById("p_cxr_preview")
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height)

    //起始點座標
    let x1 = 0
    let y1 = 0

    // 終點座標
    let x2 = 0
    let y2 = 0

    // 畫筆
    ctx.strokeStyle = 'blue'
    ctx.lineWidth = 2
    ctx.lineCap = 'round'
    ctx.lineJoin = 'round'

    // 宣告 isDrawing 為滑鼠點擊的狀態,因為我們需要滑鼠在 mousedown 的狀態時,才會監聽 mousemove 的狀態
    let isDrawing = false

    // 透過上方的 hasTouchEvent 來決定要監聽的是 mouse 還是 touch 的事件
    let upEvent = hasTouchEvent ? 'touchend' : 'mouseup'
    let outEvent = hasTouchEvent ? 'touchcancel' : 'mouseout'
    let downEvent = hasTouchEvent ? 'touchstart' : 'mousedown'
    let moveEvent = hasTouchEvent ? 'touchmove' : 'mousemove'

    canvas.addEventListener(upEvent, function(e){
      isDrawing = false
    })

    canvas.addEventListener(outEvent, function(e){
      isDrawing = false
    })

    canvas.addEventListener(downEvent, function(e){
      isDrawing = true

      x1 = e.offsetX
      y1 = e.offsetY
    })

    canvas.addEventListener(moveEvent, function(e){
      if (!isDrawing) {
        return
      }

      // 取得終點座標
      if (hasTouchEvent) {
        e.preventDefault();

        var touch = e.touches[0] || e.changedTouches[0];
        var elm = $(this).offset();
        x2 = touch.pageX - elm.left;
        y2 = touch.pageY - elm.top;
      } else {
        x2 = e.offsetX
        y2 = e.offsetY
      }

      // 開始繪圖
      ctx.beginPath()
      ctx.moveTo(x1, y1)
      ctx.lineTo(x2, y2)
      ctx.stroke()

      // 更新起始點座標
      x1 = x2
      y1 = y2
    })
};