HTML5(五)html5<canvas路径和三角函数的故事>(下)

来源:互联网 发布:日本海关数据 编辑:程序博客网 时间:2024/05/18 03:11

利用canvas的路径实现直线跟着鼠标的方向转动和点击圆,圆变大变小的功能。

<!DOCTYPE html><html><head><title>canvas</title><style>canvas{background:#ccc;}</style><script>window.onload=function(){var canvas = document.getElementById("canvas");var cobj = canvas.getContext("2d");/*功能:直线跟着鼠标的方向转动*/cobj.lineWidth=5;cobj.strokeStyle="#f00";cobj.moveTo(200,250);cobj.lineTo(200,350);cobj.stroke();canvas.onmousemove=function(e){var mx=e.layerX;var my=e.layerY;var startx=200;var starty=250;var angle=Math.atan2((my-starty),(mx-startx));cobj.clearRect(0,0,400,400);cobj.beginPath();cobj.moveTo(startx,starty);cobj.lineTo(startx+100*Math.cos(angle),starty+100*Math.sin(angle));cobj.stroke();}/*功能:点击圆,圆变大变小*//*cobj.arc(200,200,50,0,2*Math.PI);cobj.stroke();var angle=0;canvas.onclick=function(e){var mx=e.layerX;var my=e.layerY;//判断是否在路径中if(cobj.isPointInPath(mx,my)){setInterval(function(){cobj.clearRect(0,0,400,400);angle+=0.2;cobj.beginPath();cobj.arc(200,200,50+10*Math.sin(angle),0,2*Math.PI);cobj.stroke();},50)}}*/}</script></head><body><canvas width="400px" height="400px" id="canvas">请您升级浏览器</canvas></body></html>


0 0