达到一定值后如何反转该正方形的方向?

我正在尝试创建一个空闲动画,其中红色矩形在循环中稍微来回移动。由于某种原因,一旦它达到指定的阈值而不是继续向相反方向移动,它就会停止。


我做错了什么?


<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>


莫回无
浏览 91回答 3
3回答

慕虎7371278

在这里,我为您提供了一个解决方案,以实现我相信您正在尝试做的事情。使用改变大小的速度变量。X 位置总是按速度值增加。速度在屏幕边缘改变方向。// use a velocity variablevar xspeed = 1;// always increase by velocitycenterWidthPosition += xspeed;&nbsp;// screen edges are 0 and 400 in this exampleif (centerWidthPosition > 400 || centerWidthPosition < 0){&nbsp;&nbsp; &nbsp; xspeed *= -1; // change velocity direction}我在你的 if 中添加了另一个条件,这会导致对象来回反弹。删除 || 之后的选择 如果你不希望它这样做。

慕雪6442864

您的函数陷入循环;一旦 centerWidthPosition 达到 399,您的条件会使其增加回 400,然后减少回 399。

蝴蝶不菲

这是另一个作为脑筋急转弯的问题-通过使此动画在循环中弹跳将如何进行-基本上将文本转换为粒子,然后反转回文本并反转回粒子并返回文本等等,无限循环: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 neededvar 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.a.x = (random() - 0.5) * 0.8;this.a.y = (random() - 0.5) * 0.8;this.v.add(this.a);this.v.multiply(FRICT);this.x += this.v.x;this.y += this.v.y;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();}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript