本文实例为大家分享了
xml/html code
复制内容到剪贴板
<!doctypehtml> <html> <head> <metachart=“utf我喜爱的书刊读者-8”/> <metahttp-equiv=“x-ua-compatible”content=“ie=edge”/> <title>canvas实现跟随鼠标旋转的箭头</title> <style> *{padding:0;margin:0} </style> </head> <body> <canvaswidth=“500”height=“500”style=“border:1pxsolid#555;display:block;margin:0auto;”></canvas> <script> vararrow=function(){ this.x=0; this.y=0; this.color=“#f90” this.rolation=0; } varcanvas=document.querylector(‘canvas’) varctx=canvas.g想和你去吹吹风歌词etcontext(‘2d’); arrow.prototype.draw=function(ctx){ ctx.save(); ctx.translate(this.x,this.y); ctx.rotate(this.rolation) ctx.fillstyle=this.color; ctx.beginpath(); ctx.moveto(0,15); ctx.lineto(-50,15); ctx.lineto(-50,-15); ctx.lineto(0,-15); ctx.lineto(0,-35); ctx.lineto(50,0); ctx.lineto(0,35); ctx.clopath() ctx.fill(); ctx.restore(); } vararrow=newarrow(); arrow.x=canvas.width/2; arrow.y=canvas.height/2; varc_x,c_y;//相对于canvas坐标的位置; varismoudown=fal; arrow.draw(ctx) canvas.addeventlistener(‘moudown’,function(e){ ismoudown=true; },fal) canvas.addeventlistener(‘moumove’,function(e){ if(ismoudown==true){ c_x=getpos(e).x-canvas.offtleft; c_y=getpos(e).y-canvas.offttop; //tinterval(drawfram,1000/60) requestanimationframe(drawfram) } },fal) canvas.addeventlistener(‘mouup’,function(e){ ismoudown=fal; },fal) functiondrawfram(){ vardx=c_x-arrow.x; vardy=c_y-arrow.y; arrow.rolation=math.atan2(dy,dx); ctx.clearrect(0,中国梦演讲稿0,canvas.width,canvas.height); arrow.draw(ctx) } functiongetpos(e){ varmou={x:0,y:0} varee=e||event; if(e.pagex||e.pagey){ mou.x=e.pagex; mou.y=e.pagey; }el{ mou.x=省考考试科目e.pagex+document.body.scrollleft+document.document.documentelement.scrollleft; mou.y=e.pagey+document.body.scrolltop+document.document.documentelement.scrolltop; } returnmou; } </script> </body> </html> demo地址:http://codepen.io/jonechen/pen/ezp斤和两的换算gwd
不废话,直接上demo了,这个效果实现起来并不复杂,但是麻雀随小,五脏俱全,主要涉及到的知识点有:
1、canvas的基本绘图;
2、js各个事件的监听;
3、js动画;
4、三角函数结合js在canvas中的基本应用;
以上就是本文的全部内容,希望对大家的学习有所帮助。
原文: