本文实例为大家分享了
xml/html code复制内容到剪贴板
nbsp;html> html> head> meta charset=utf-8 /> meta http-equiv=x-ua-compatible content=ie=edge /> title>canvas实现跟随鼠标旋转的箭头title> style> *{padding: 0;margin: 0} style> head> body> canvas width=500 height=500 style=border: 1px solid #555; display: block;margin: 0 auto;>canvas> script> var arrow=function () { this.x=0; this.y=0; this.color=#f90 this.rolation=0; } var canvas=document.queryselector('canvas') var ctx=canvas.getcontext('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.closepath() ctx.fill(); ctx.restore(); } var arrow=new arrow(); arrow.x=canvas.width/2; arrow.y=canvas.height/2; var c_x,c_y; //相对于canvas坐标的位置; var ismousedown=false; arrow.draw(ctx) canvas.addeventlistener('mousedown',function(e) { ismousedown=true; },false) canvas.addeventlistener('mousemove',function(e) { if(ismousedown==true){ c_x=getpos(e).x-canvas.offsetleft; c_y=getpos(e).y-canvas.offsettop; //setinterval(drawfram,1000/60) requestanimationframe(drawfram) } },false) canvas.addeventlistener('mouseup',function(e) { ismousedown=false; },false) function drawfram(){ var dx=c_x-arrow.x; var dy=c_y-arrow.y; arrow.rolation=math.atan2(dy,dx); ctx.clearrect(0,0,canvas.width,canvas.height); arrow.draw(ctx) } function getpos(e) { var mouse={x:0,y:0} var ee=e||event; if(e.pagex||e.pagey){ mouse.x=e.pagex; mouse.y=e.pagey; }else{ mouse.x=e.pagex+document.body.scrollleft+document.document.documentelement.scrollleft; mouse.y=e.pagey+document.body.scrolltop+document.document.documentelement.scrolltop; } return mouse; } script> body> html>
demo地址:http://codepen.io/jonechen/pen/ezpgwd
不废话,直接上demo了,这个效果实现起来并不复杂,但是麻雀随小,五脏俱全,主要涉及到的知识点有:
1、canvas的基本绘图;
2、js各个事件的监听;
3、js动画;
4、三角函数结合js在canvas中的基本应用;
以上就是本文的全部内容,希望对大家的学习有所帮助。
原文:http://www.cnblogs.com/jone-chen/p/5243439.html