可以查看demo:http://sandbox.runjs.cn/show/hjb2hzzx(建议查看console查看点击后的改变)
具体原理是每次点击的时候去判断当前的鼠标坐标是属于哪一个路径下的,对当前的这个形状改变状态。
for (var i = 0; i < drawData.length; i++) { drawSingleCircle(i); if (ctx.isPointInPath(x, y)) { changeStatus(i); } }
参考:http://www.imooc.com/video/4320/227
关键代码:
(function(window) { var document = window.document; var clientW = window.innerWidth; var clientH = window.innerHeight; var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); canvas.width = clientW; canvas.height = clientH; var drawData = []; // 存数据 // 添加数据 function addData() { for (var i = 0; i < 10; i++) { var data = { id: i, type: 'arc', x: Math.random() * canvas.width, y: Math.random() * canvas.height, radius: Math.random() * 50 + 20 }; drawData.push(data); } } // 画圆 function drawCircle() { addData(); ctx.clearRect(0,0,canvas.width,canvas.height); for (var i = 0; i < drawData.length; i++) { drawSingleCircle(i); } } drawCircle(); // 画单个圆 function drawSingleCircle(i){ ctx.beginPath(); ctx.arc(drawData[i].x, drawData[i].y, drawData[i].radius, 0, Math.PI * 2, true); ctx.fillStyle = '#000'; ctx.fill(); ctx.closePath(); } // 重新绘制(点击事件中需要用到) function reDraw(x, y) { ctx.clearRect(0,0,canvas.width,canvas.height); for (var i = 0; i < drawData.length; i++) { drawSingleCircle(i); if (ctx.isPointInPath(x, y)) { changeStatus(i); } } } // 如果在事件触发的范围内,可以做一些事情来改变状态 function changeStatus(i){ ctx.fillStyle = "#f00"; ctx.fill(); console.log(drawData[i].type); console.log('你点击了第' + i + '个'); } // 点击事件处理函数 function onClick(event) { var e = event || window.event; var x = e.clientX - canvas.getBoundingClientRect().left; var y = e.clientY - canvas.getBoundingClientRect().top; reDraw(x, y); } // 注册点击事件 canvas.addEventListener('click',onClick,false); })(window);