一、Canvas事件綁定說明
canvas元素和CanvasRenderingContext2D 上下文對象,處理的是位圖、像素數據,只有一個標簽。
所有的交互,判斷處理都是針對cavans標簽的。
對於交互性要求比較高的應用場景推薦使用svg矢量圖模式。
canvas交互邏輯需要自己編碼處理,當點擊事件發生時,重繪所有圖形。 時間對接方法有:isPointInPath(), isPontInStore().
isPontInPath()
context.isPointInPath(x, y);
context.isPointInPath(x, y, fillRule);
此方法返回Boolean值。
參數
各個參數含義和作用如下:
xNumber
用來檢測的點的橫坐標。
yNumber
用來檢測的點的縱坐標。
fillRuleString
填充規則。用來確定一個點實在路徑內還是路徑外。可選值包括:
nonzero:非零規則,此乃默認規則。
evenodd:奇偶規則。
isPointInStore()
context.isPointInStroke(x, y);
context.isPointInStroke(path, x, y);
此方法返回Boolean值。
參數
各個參數含義和作用如下:
xNumber
用來檢測的點的橫坐標。
yNumber
用來檢測的點的縱坐標。
pathObject
指Path2D對象。
二、 Canvas 事件綁定示例
1. 鼠標划線
<canvas id="canvasOne" style="border:1px solid red;" width="500" height="300"></canvas> <script> var canvas = document.querySelector('canvas'); var ctx = canvas.getContext('2d'); var isMove = false; //鼠標事件 canvas.onmousedown = function (e) { var x = e.clientX; var y = e.clientY; ctx.moveTo(x, y); isMove = true; } canvas.onmousemove = function (e) { var x = e.clientX; var y = e.clientY; if (isMove) { ctx.lineTo(x, y); ctx.stroke(); } } canvas.onmouseup = function (e) { isMove = false; } </script>
2.可移動的矩形
<canvas id="canvasOne" style="border:1px solid red;" width="500" height="300"></canvas> <script> var canvas = document.querySelector('canvas'); var ctx = canvas.getContext('2d'); ctx.rect(100, 100, 100, 100); ctx.fill(); var isMove = false; var spanX = 0, spanY = 0; var lastX=100,lastY=100; //鼠標事件 canvas.onmousedown = function (e) { var x = e.clientX; var y = e.clientY; ctx.moveTo(x, y); spanX = x - lastX; spanY = y - lastY; isMove = true; } canvas.onmousemove = function (e) { var x = e.clientX; var y = e.clientY; // if ( ctx.isPointInPath(x, y)) { // ctx.fillStyle = 'red'; // ctx.fill(); // }else{ // ctx.fillStyle = 'black'; // ctx.fill(); // } if (isMove) { if (ctx.isPointInPath(x, y)) { lastX=x-spanX; lastY=y-spanY; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.rect(lastX,lastY, 100, 100); ctx.fill(); ctx.closePath(); } } } canvas.onmouseup = function (e) { isMove = false; } </script>
更多: