是否有可能得到的信息,如果是点击画布行?
var canvas; var x = 200; var y = 200; var dx=4; var dy=4; var d = 5; var width, height; function init() { canvasE = document.getElementById('game'); canvas= canvasE.getContext('2d'); width = canvasE.width; height = canvasE.height; canvasE.addEventListener("click", onClick, false); drawCircle(); } function drawCircle() { clear(); canvas.arc(x-1,y-1,d,0,Math.PI*2,true); canvas.beginPath(); canvas.arc(x-1,y-1,d,0,Math.PI*2,true); canvas.closePath(); canvas.fill(); canvas.beginPath(); canvas.moveTo(20,20); canvas.lineTo(150,100); canvas.stroke(); //check if click coords within current path if(canvas.isPointInPath(x,y)) { document.getElementById("inPath").innerHTML = "yes"; } else { document.getElementById("inPath").innerHTML = "no"; } canvas.closePath(); } function clear() { canvas.fillStyle="#ffffff"; canvas.fillRect(0,0,width,height); canvas.fillStyle="#ff0000"; canvas.strokeRect(0,0,width,height); } function onClick(e) { var element = canvasE; var offsetX = 0, offsetY = 0 if (element.offsetParent) { do { offsetX += element.offsetLeft; offsetY += element.offsetTop; } while ((element = element.offsetParent)); } x = e.pageX - offsetX; y = e.pageY - offsetY; drawCircle(); document.getElementById("info").value = "x: " + x + ", y: " + y; } init();
canvas, input { margin: 10px; text-align: center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <input id="info" type="text" readonly> <span id="inPath">No</span> <canvas id="game" width="500" height="500"></canvas>
谢谢