canvas中的三角運動(3) —— 正弦波運動

Rod8448 8年前發布 | 8K 次閱讀 JavaScript開發 canvas

一. 需求:

要求:讓小球沿著正弦波運動。

小球的構造函數如下:

// 圓球的構造函數
function Ball(radius, color) {
    if(radius === undefined) { radius = 40; }
    if(color === undefined) { color = "#ff0000"; }
    this.x = 0;
    this.y = 0;
    this.radius = radius;
    this.rotation = 0;
    this.scaleX = 1;
    this.scaleY = 1;
    this.color = color;
    this.lineWidth = 1;
}
Ball.prototype.draw = function(context) {
    context.save();
    context.translate(this.x, this.y);
    context.rotate(this.rotation);
    context.scale(this.scaleX, this.scaleY);
    context.lineWidth = this.lineWidth;
    context.fillStyle = this.color;
    context.beginPath();
    context.arc(0, 0, this.radius, 0, Math.PI * 2, true);
    context.closePath();
    context.fill();
    if(this.lineWidth > 0) {
        context.stroke();
    }
    context.restore();
}

二. 思路分析:

正弦波的實現可以使用正弦函數 Math.sin(angle) 繪制。其中, angle值作為變量并遞增時,即可使物體按正弦曲線運動,從而實現正弦波動畫 。

過程如下:

(function drawFrame() {
    window.requestAnimationFrame(drawFrame, canvas);
    ball.y = Math.sin(angle) * range;
    angle += speed;
    ball.draw(context);
})();

可以在控制臺中輸出以下代碼,了解下正弦波的數值分布:

var fullRadians = Math.PI * 2;
for(var angle = 0; angle < fullRadians; angle += 0.01) {
    console.log(Math.sin(angle));
}

三. 實例:

代碼:

<canvas id="canvas" width="400" height="400" style="background: #ccc;"></canvas>

window.onload = function() { var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"), ball = new Ball(2), angle = 0, range = 50, speed = 0.1, isFoward = true;

    ball.x = 0;
    ball.y = canvas.height / 2;
    ball.lineWidth = 0;

(function drawFrame() {
    window.requestAnimationFrame(drawFrame, canvas);
    // context.clearRect(0, 0, canvas.width, canvas.height);
    ball.y = canvas.height / 2 + Math.sin(angle) * 100;
    if(isFoward) {
        ball.x += speed * 20;
    } else {
        ball.x -= speed * 20;
    }

    if(ball.x > canvas.width) {
        isFoward = false;
        context.clearRect(0, 0, canvas.width, canvas.height);
    } else if(ball.x < 0) {
        isFoward = true;
        context.clearRect(0, 0, canvas.width, canvas.height);
    }
    angle += speed;
    ball.draw(context);
})();

};</code></pre>

演示如下: http://codepen.io/dengzhirong/pen/xOZypy

四. 總結:

創建正弦波的方法,就是使用正弦函數 Math.sin(angle) 求值,并讓弧度值angle根據運動時間遞增。

創建正弦波的公式如下:

/**

  • range:正選的波峰值
  • center:y軸的交點
  • speed:正弦波的運動速度
  • angle:弧度值,遞增的變量 */ (function drawFrame() { window.requestAnimationFrame(drawFrame, canvas);

    valeue = center + Math.sin(angle) * range; angle += speed; })();</code></pre>

     

    來自:http://www.dengzhr.com/js/956

     

    Save

 本文由用戶 Rod8448 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!