新手求助html5 canvas画布的鼠标单击事件,谢谢!

在页面中添加一个width = "500" height = "500"的canvas,
然后在(100,100)画一个长40高20的矩形
需要鼠标单击这个矩形,能打开一个链接,
<!doctype html>
<html>
<head></head>
<body>
<canvas id="test" width="500" height="500" style = "border:1px solid red"></canvas>
<script>
var canvas=document.getElementById('canvas');
var cxt=canvas.getContext('2d');
cxt.fillRect(100,100,40,20);
</script>
</body>
</html>
单击时间怎么写?谢谢各位

慕姐4208626
浏览 639回答 1
1回答

Cats萌萌

只能获取鼠标对于画布的事件,可以根据点击范围判断点击的内容,然后做相应操作1234567891011121314151617181920212223<!doctype&nbsp;html><html><head></head><body><canvas&nbsp;id="canvas"&nbsp;width="500"&nbsp;height="500"&nbsp;style&nbsp;=&nbsp;"border:1px&nbsp;solid&nbsp;red"></canvas><script>var&nbsp;rect={x:100,y:100,w:40,h:20};//定义要画的矩形的位置属性var&nbsp;canvas=document.getElementById('canvas');var&nbsp;cxt=canvas.getContext('2d');cxt.fillRect(rect.x,rect.y,rect.w,rect.h);//绘制矩形canvas.onclick=function(e){//给canvas添加点击事件&nbsp;&nbsp;&nbsp;&nbsp;e=e||event;//获取事件对象&nbsp;&nbsp;&nbsp;&nbsp;//获取事件在canvas中发生的位置&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;x=e.clientX-canvas.offsetLeft;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;y=e.clientY-canvas.offsetTop;&nbsp;&nbsp;&nbsp;&nbsp;//如果事件位置在矩形区域中&nbsp;&nbsp;&nbsp;&nbsp;if(x>=rect.x&&x<=rect.x+rect.w&&y>=rect.y&&y<=rect.y+rect.h){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;window.open('链接地址');//打开指定链接&nbsp;&nbsp;&nbsp;&nbsp;}}</script></body></html>&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5