(1)事件问题:我们无法通过JS给画布里面的图像绑定事件。
ctx.isPointInPath(x,y) //我们可以通过这个条件判断触发条件是否在此路径上来添加事件//但是需要记得路径的问题,清除路径。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } html,body{ height: 100%; overflow: hidden; } body{ background: pink; } #test{ background: gray; position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; } </style> </head> <body> <canvas id="test" width="300" height="300"> <span>您的浏览器不支持画布元素 请您换成萌萌的谷歌</span> </canvas> </body> <script type="text/javascript"> window.onload=function(){ //querySelector身上有坑 //拿到画布 var canvas = document.querySelector("#test"); if(canvas.getContext){ var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.arc(100,100,50,0,360*Math.PI/180); ctx.fill(); ctx.beginPath(); ctx.arc(200,200,50,0,360*Math.PI/180); ctx.fill(); canvas.onclick=function(ev){ ev = ev||event; var x = ev.clientX - canvas.offsetLeft; var y = ev.clientY - canvas.offsetTop; if(ctx.isPointInPath(x,y)){ alert(123); } } } } </script> </html>
(2)图像导出,本事canvas画布就是一个图片可以直接另存为
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } html,body{ height: 100%; overflow: hidden; } body{ background: pink; } #test{ background: gray; position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; } </style> </head> <body> <canvas id="test" width="300" height="300"> <span></span> </canvas> </body> <script type="text/javascript"> window.onload=function(){ var canvas = document.querySelector("#test"); if(canvas.getContext){ var ctx = canvas.getContext("2d"); ctx.fillRect(0,0,199,199); var result = canvas.toDataURL(); console.log(result); } } </script> </html>