路上的杨柳依然神彩奕奕的低垂着黄绿色的发丝,好像冬天的降温没带给她们多少伤害。我倒感受到她们内心的寒冷,叶子摸着十分冰冷,也缺少了昔日的水分。冬天的到来,摧残了多少无辜的生命,又演绎了多少生命的童话。
本文实例为大家分享了
XML/HTML Code复制内容到剪贴板
- <!DOCTYPEhtml>
- <html>
- <head>
- <metacharset="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.querySelector('canvas')
- varctx=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();
- }
- varArrow=newarrow();
- Arrow.x=canvas.width/2;
- Arrow.y=canvas.height/2;
- varc_x,c_y;//相对于canvas坐标的位置;
- varisMouseDown=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)
- 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){
- varmouse={x:0,y:0}
- varee=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;
- }
- returnmouse;
- }
- </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