欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

html5 canvas实现跟随鼠标旋转的箭头_html5教程技巧

程序员文章站 2022-04-16 16:44:55
...
本文实例为大家分享了
XML/HTML Code复制内容到剪贴板
  1. /span>>
  2. html>
  3. head>
  4. meta charset="utf-8" />
  5. meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. title>canvas实现跟随鼠标旋转的箭头title>
  7. style>
  8. *{padding: 0;margin: 0}
  9. style>
  10. head>
  11. body>
  12. canvas width="500" height="500" style="border: 1px solid #555; display: block;margin: 0 auto;">canvas>
  13. script>
  14. var arrow=function () {
  15. this.x=0;
  16. this.y=0;
  17. this.color="#f90"
  18. this.rolation=0;
  19. }
  20. var canvas=document.querySelector('canvas')
  21. var ctx=canvas.getContext('2d');
  22. arrow.prototype.draw=function (ctx) {
  23. ctx.save();
  24. ctx.translate(this.x,this.y);
  25. ctx.rotate(this.rolation)
  26. ctx.fillStyle=this.color;
  27. ctx.beginPath();
  28. ctx.moveTo(0, 15);
  29. ctx.lineTo(-50, 15);
  30. ctx.lineTo(-50, -15);
  31. ctx.lineTo(0,-15);
  32. ctx.lineTo(0,-35);
  33. ctx.lineTo(50,0);
  34. ctx.lineTo(0,35);
  35. ctx.closePath()
  36. ctx.fill();
  37. ctx.restore();
  38. }
  39. var Arrow=new arrow();
  40. Arrow.x=canvas.width/2;
  41. Arrow.y=canvas.height/2;
  42. var c_x,c_y; //相对于canvas坐标的位置;
  43. var isMouseDown=false;
  44. Arrow.draw(ctx)
  45. canvas.addEventListener('mousedown',function(e) {
  46. isMouseDown=true;
  47. },false)
  48. canvas.addEventListener('mousemove',function(e) {
  49. if(isMouseDown==true){
  50. c_x=getPos(e).x-canvas.offsetLeft;
  51. c_y=getPos(e).y-canvas.offsetTop;
  52. //setInterval(drawFram,1000/60)
  53. requestAnimationFrame(drawFram)
  54. }
  55. },false)
  56. canvas.addEventListener('mouseup',function(e) {
  57. isMouseDown=false;
  58. },false)
  59. function drawFram(){
  60. var dx=c_x-Arrow.x;
  61. var dy=c_y-Arrow.y;
  62. Arrow.rolation=Math.atan2(dy,dx);
  63. ctx.clearRect(0,0,canvas.width,canvas.height);
  64. Arrow.draw(ctx)
  65. }
  66. function getPos(e) {
  67. var mouse={x:0,y:0}
  68. var ee=e||event;
  69. if(e.pageX||e.pageY){
  70. mouse.x=e.pageX;
  71. mouse.y=e.pageY;
  72. }else{
  73. mouse.x=e.pageX+document.body.scrollLeft+document.document.documentElement.scrollLeft;
  74. mouse.y=e.pageY+document.body.scrollTop+document.document.documentElement.scrollTop;
  75. }
  76. return mouse;
  77. }
  78. script>
  79. body>
  80. 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