1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
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 }) }; |