1. 程式人生 > >canvas 使用 isPointInPath() 判斷鼠標位置是否在繪制的元素上

canvas 使用 isPointInPath() 判斷鼠標位置是否在繪制的元素上

div 畫布 sha posit 不支持 getc rip 一次 通過

canvas 裏繪制的圖形不是一個實體 DOM,所以要給每個繪制的圖形添加事件操作比給 DOM 添加事件要復雜很多。

所以,我們需要使用一個 canvas 的 isPointInPath(x, y) 方法,來獲取鼠標相對於瀏覽器的坐標,然後還需要計算出鼠標相對於 canvas 畫布的坐標,最後通過 isPointInPath(x, y) 方法判斷此坐標是否在繪制的元素上,進行相應的操作。

isPointInPath() 方法是針對的當前繪制的路徑,而鼠標在執行操作的時候,我們會根據需要監聽鼠標的事件,當鼠標事件符合我們要求的時候,就對畫布進行重繪。在重繪的時候,每畫一條路徑就調用一次 isPointInPath(x, y) 方法,判斷鼠標操作的點是不是在這個繪制的元素身上,如果在,就可以對當前繪制的這個元素進行自定義操作了。

以下是繪制兩個圖形,並監聽 mousemove 事件,來判斷鼠標是否在圖形上的 demo:

<style type="text/css">
*{margin:0;padding:0;}
.canvas-box {position: relative;}
canvas {box-shadow: 0 0 10px rgba(0,0,0,0.2) }
</style>

<div class="canvas-box"> 
 <canvas id="cvs" width="500" height="400">不支持canvas</canvas>
</div>

<
script> var cvs = document.getElementById(cvs); var ctx = cvs.getContext(2d); // 封裝繪制的圖形 function draw () { ctx.fillStyle = #000; ctx.beginPath(); ctx.moveTo(100,100); ctx.bezierCurveTo(110,110,199,278,300,379); ctx.lineTo(400,100) ctx.closePath(); } function circle () { ctx.fillStyle = #000; ctx.beginPath(); ctx.arc(
100,200,50,0,Math.PI*2) ctx.closePath(); } // 初始化繪制圖形 draw(); ctx.fill() circle(); ctx.fill() var fns = [draw,circle]; // 監聽鼠標事件 cvs.onmousemove = function (e) { // 得到鼠標的坐標 var x = e.pageX, y =e.pageY; ctx.clearRect(0,0,400,300) // 遍歷繪制圖形 for(var i = fns.length; i--;) { fns[i](); // 每繪制一個圖形就判斷一次當前鼠標的坐標是否在這個圖形上,然後進行自定義操作 if(ctx.isPointInPath(x,y)) { ctx.fillStyle = "#f00" } else { ctx.fillStyle = "#000" } ctx.fill() } } </script>

canvas 使用 isPointInPath() 判斷鼠標位置是否在繪制的元素上