I'm trying to create an idle animation where the red rectangle moves back and forth slightly in a loop. For some reason once it reaches the specified threshhold instead of proceeding to move in the opposite direction, it just stops.
What did I do wrong?
<canvas id="myCanvas" width="1500" height="500" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Spaceship structure
var shipWidth = 250;
var shipHeight = 100;
// Canvas parameters
var cWidth = canvas.width;
var cHeight = canvas.height;
// Positioning variables
var centerWidthPosition = (cWidth / 2) - (shipWidth / 2);
var centerHeightPosition = (cHeight / 2) - (shipHeight / 2);
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function drawShip(){
ctx.clearRect(0, 0, cWidth, cHeight);
ctx.fillStyle = "#FF0000";
ctx.fillRect(centerWidthPosition,centerHeightPosition,shipWidth,shipHeight);
centerWidthPosition--;
if (centerWidthPosition < 400){
++centerWidthPosition;
}
requestAnimationFrame(drawShip);
}
drawShip();
</script>
@TheAmberlamps explained why it's doing that. Here I offer you a solution to achieve what I believe you are trying to do.
Use a velocity variable that changes magnitude. X position always increases by velocity value. Velocity changes directions at screen edges.
// use a velocity variable
var xspeed = 1;
// always increase by velocity
centerWidthPosition += xspeed;
// screen edges are 0 and 400 in this example
if (centerWidthPosition > 400 || centerWidthPosition < 0){
xspeed *= -1; // change velocity direction
}
I added another condition in your if that causes the object to bounce back and forth. Remove the selection after ||if you don't want it doing that.
Your function is caught in a loop; once centerWidthPosition reaches 399 your conditional makes it increment back up to 400, and then it decrements back to 399.
here is another one as a brain teaser - how would go by making this animation bounce in the loop - basically turn text into particles and then reverse back to text and reverse back to particles and back to text and so on and on and on infinitely:
var random = Math.random; window.onresize = function () { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }; window.onresize(); var ctx = canvas.getContext('2d'); ctx.font = 'bold 50px "somefont"'; ctx.textBaseline = 'center'; ctx.fillStyle = 'rgba(255,255,255,1)'; var _particles = []; var particlesLength = 0; var currentText = "SOMETEXT"; var createParticle = function createParticle(x, y) {_particles.push(new Particle(x, y));}; var checkAlpha = function checkAlpha(pixels, i) {return pixels[i * 4 + 3] > 0;}; var createParticles = function createParticles() { var textSize = ctx.measureText(currentText); ctx.fillText(currentText,Math.round((canvas.width / 2) - (textSize.width / 2)),Math.round(canvas.height / 2)); var imageData = ctx.getImageData(1, 1, canvas.width, canvas.height); var pixels = imageData.data; var dataLength = imageData.width * imageData.height; for (var i = 0; i < dataLength; i++) { var currentRow = Math.floor(i / imageData.width); var currentColumn = i - Math.floor(i / imageData.height); if (currentRow % 2 || currentColumn % 2) continue; if (checkAlpha(pixels, i)) { var cy = ~~(i / imageData.width); var cx = ~~(i - (cy * imageData.width)); createParticle(cx, cy); }} particlesLength = _particles.length; }; var Point = function Point(x, y) { this.set(x, y); }; Point.prototype = { set: function (x, y) { x = x || 0; y = y || x || 0; this._sX = x; this._sY = y; this.reset(); }, add: function (point) { this.x += point.x; this.y += point.y; }, multiply: function (point) { this.x *= point.x; this.y *= point.y; }, reset: function () { this.x = this._sX; this.y = this._sY; return this; }, }; var FRICT = new Point(0.98);//set to 0 if no flying needed var Particle = function Particle(x, y) { this.startPos = new Point(x, y); this.v = new Point(); this.a = new Point(); this.reset(); }; Particle.prototype = { reset: function () { this.x = this.startPos.x; this.y = this.startPos.y; this.life = Math.round(random() * 300); this.isActive = true; this.v.reset(); this.a.reset(); }, tick: function () { if (!this.isActive) return; this.physics(); this.checkLife(); this.draw(); return this.isActive; }, checkLife: function () { this.life -= 1; this.isActive = !(this.life < 1); }, draw: function () { ctx.fillRect(this.x, this.y, 1, 1); }, physics: function () { if (performance.now()<nextTime) return; this.ax = (random() - 0.5) * 0.8; this.ay = (random() - 0.5) * 0.8; this.v.add(this.a); this.v.multiply(FRICT); this.x += this.vx; this.y += this.vy; this.x = Math.round(this.x * 10) / 10; this.y = Math.round(this.y * 10) / 10; } }; var nextTime = performance.now()+3000; createParticles(); function clearCanvas() { ctx.fillStyle = 'rgba(0,0,0,1)'; ctx.fillRect(0, 0, canvas.width, canvas.height); } (function clearLoop() { clearCanvas(); requestAnimationFrame(clearLoop); })(); (function animLoop(time) { ctx.fillStyle = 'rgba(255,255,255,1)'; var isAlive = true; for (var i = 0; i < particlesLength; i++) { if (_particles[i].tick()) isAlive = true; } requestAnimationFrame(animLoop); })(); function resetParticles() { for (var i = 0; i < particlesLength; i++) { _particles[i].reset(); }}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.