zoukankan      html  css  js  c++  java
  • Canvas学习笔记——动画中的三角学

    示例1,跟随鼠标的键头:

     
    需要掌握一个重要的公式,这个方法返回从 x 轴到点 (x,y) 之间的角度
    Math.atan2(dy,dx);

    关键代码:

     1 function Arrow() {
     2   this.x = 0;
     3   this.y = 0;
     4   this.rotate = 0;
     5   this.color = '#ffff00';
     6 }
     7 
     8 Arrow.prototype.draw = function(context) {
     9   context.save();
    10   context.translate(this.x, this.y);
    11   context.rotate(this.rotate);
    12   context.fillStyle = this.color;
    13   context.lineWidth = 2;
    14 
    15   context.beginPath();
    16   context.moveTo( - 50, -25);
    17   context.lineTo(0, -25);
    18   context.lineTo(0, -50);
    19   context.lineTo(50, 0);
    20   context.lineTo(0, 50);
    21   context.lineTo(0, 25);
    22   context.lineTo( - 50, 25);
    23   context.closePath();
    24 
    25   context.fill();
    26   context.stroke();
    27   context.restore();
    28 };
    29 
    30 var canvas = document.getElementById('c'),
    31 context = canvas.getContext('2d'),
    32 mouse = utils.captureMouse(canvas),
    33 arrow = new Arrow();
    34 
    35 arrow.x = canvas.width / 2;
    36 arrow.y = canvas.height / 2;
    37 
    38 (function draw() {
    39     window.requestAnimFrame(draw, canvas);
    40     context.clearRect(0, 0, canvas.width, canvas.height);
    41 
    42     var dx = mouse.x - arrow.x,
    43     dy = mouse.y - arrow.y,
    44     rotate = Math.atan2(dy, dx);
    45 
    46     arrow.rotate = rotate;
    47 
    48     arrow.draw(context);
    49 })();
    View Code

    示例2,平滑运动:

    关键代码

    yPos = centerY + Math.sin(angle) * range;
    angle += 0.1;

    示例3,脉冲运动:

    需要注意,这里不需要清除画布,并且在开始绘制时应该使用beginPath()

     

    示例4,圆周运动:

     
     

    圆周运动的要点是用正弦来计算x坐标,余弦来算y坐标,椭圆则是x轴的运动和y轴的半径不同。

  • 相关阅读:
    ReentrantLock与synchronized的差别
    读TIJ -1 对象入门
    wikioi 2573 大顶堆与小顶堆并用
    开源 免费 java CMS
    UVA10972
    springboot5
    spring-boot4
    spring-boot3
    spring-boot2
    spring-boot1
  • 原文地址:https://www.cnblogs.com/undefined000/p/5117150.html
Copyright © 2011-2022 走看看