canvas中的三角运动(4) —— 脉冲运动
<h2>需求:</h2> <p>模拟球形的脉冲运动。</p> <p>小球的构造函数如下:</p> <pre> <code class="language-java">// 圆球的构造函数 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(); }</code></pre> <h2>二. 思路分析:</h2> <p>使用正弦值改变球形的比例,即可制造出脉冲效果。</p> <p>如下:</p> <pre> <code class="language-java"><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> <p>演示如下: <a href="/misc/goto?guid=4959677072568858255" rel="nofollow,noindex">http://codepen.io/dengzhirong/pen/PzgygG</a></p> <p> </p> <p>来自:http://www.dengzhr.com/js/959</p> <p> </p>
本文由用户 forever 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!