当前位置:   article > 正文

js canvas 自定义飞行轨迹 ,线性流动_使用canvas绘制飞机航行

使用canvas绘制飞机航行
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style>
  5. canvas {
  6. border: 1px solid black;
  7. }
  8. </style>
  9. </head>
  10. <body>
  11. <canvas id="myCanvas" width="300" height="200"></canvas>
  12. <script>
  13. const canvas = document.getElementById('myCanvas');
  14. const ctx = canvas.getContext('2d');
  15. // 三个点的坐标
  16. const points = [
  17. { x: 25, y: 121 },
  18. { x: 135, y: 34 },
  19. { x: 259, y: 141 }
  20. ];
  21. let t = 0;
  22. const animationSpeed = 0.005;
  23. // let isAnimating = true;
  24. // const animationDuration = 3000; // 每次动画的持续时间(毫秒)
  25. function drawCurve() {
  26. // if (!isAnimating) return;
  27. ctx.clearRect(0, 0, canvas.width, canvas.height);
  28. // 绘制控制点
  29. ctx.fillStyle = 'blue';
  30. for (const point of points) {
  31. ctx.beginPath();
  32. ctx.arc(point.x, point.y, 5, 0, Math.PI * 2);
  33. ctx.fill();
  34. }
  35. // 计算贝塞尔曲线上的坐标
  36. const x = (1 - t) * (1 - t) * points[0].x + 2 * (1 - t) * t * points[1].x + t * t * points[2].x;
  37. const y = (1 - t) * (1 - t) * points[0].y + 2 * (1 - t) * t * points[1].y + t * t * points[2].y;
  38. // 绘制移动的点
  39. ctx.fillStyle = 'red';
  40. ctx.beginPath();
  41. ctx.arc(x, y, 8, 0, Math.PI * 2);
  42. ctx.fill();
  43. // 绘制贝塞尔曲线
  44. ctx.strokeStyle = 'black';
  45. ctx.lineWidth = 2;
  46. ctx.beginPath();
  47. ctx.moveTo(points[0].x, points[0].y);
  48. ctx.quadraticCurveTo(points[1].x, points[1].y, points[2].x, points[2].y);
  49. ctx.stroke();
  50. t += animationSpeed;
  51. if (t > 1) {
  52. t = 0;
  53. // isAnimating = false; // 暂停动画
  54. // setTimeout(() => {
  55. // isAnimating = true; // 重新开始动画
  56. // requestAnimationFrame(drawCurve);
  57. // }, animationDuration);
  58. }
  59. requestAnimationFrame(drawCurve);
  60. }
  61. // 点击获取坐标
  62. canvas.addEventListener('click', (event) => {
  63. const rect = canvas.getBoundingClientRect();
  64. const mouseX = event.clientX - rect.left;
  65. const mouseY = event.clientY - rect.top;
  66. console.log('点击坐标:', mouseX, mouseY);
  67. });
  68. drawCurve();
  69. </script>
  70. </body>
  71. </html>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/536731
推荐阅读
相关标签
  

闽ICP备14008679号