canvas中的三角運動(4) —— 脈沖運動

forever 8年前發布 | 4K 次閱讀 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();
}

二. 思路分析:

使用正弦值改變球形的比例,即可制造出脈沖效果。

如下:

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

var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"), ball = new Ball(), angle = 5, centerScale = 1, range = 0.5, speed = 0.05;

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

(function drawFrame() { window.requestAnimationFrame(drawFrame, canvas); context.clearRect(0, 0, canvas.width, canvas.height); ball.scaleX = ball.scaleY = centerScale + Math.sin(angle) * range; angle += speed; ball.draw(context); })();</code></pre>

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

 

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

 

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