Josema_23
Josema_23

Reputation: 306

Make an animated square with canvas

I'm trying to make my "YellowTrack" var move, bu I'm getting crazy and i can't achieve it. I don't know why, but the "y" coordinate doesn't update, so It doesn't move. I've tried a lot of cases but any of them could solve the movement problen Could anybody help me? PD: Sorry for my bad code writing

The code is below:

function startGame() {

myGameLines1 = new DrawingLines(200, 0, 200, 600, "black");
myGameLines2 = new DrawingLines(350, 0, 350, 600, "black");
myGameLines3 = new DrawingLines(500, 0, 500, 600, "black");
myGameLines4 = new DrawingLines(650, 0, 650, 600, "black");
myGameLines5 = new DrawingLines(800, 0, 800, 600, "black");

myGameFinalLine = new FinalLine(100, 500, 800, 20, "purple");

myGameFixedSquare1 = new DrawingFixedSquares(171, 475, 60, 60, "yellow");  
myGameFixedSquare2 = new DrawingFixedSquares(321, 475, 60, 60, "red");
myGameFixedSquare3 = new DrawingFixedSquares(471, 475, 60, 60, "#F34621");
myGameFixedSquare4 = new DrawingFixedSquares(621, 475, 60, 60, "blue");
myGameFixedSquare5 = new DrawingFixedSquares(771, 475, 60, 60, "green");

myGameArea.start();


YellowTrack = new DrawingFixedSquares(171, 200, 60, 60, "yellow");

animate(YellowTrack, canvas, ctx, startTime);   

}

var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
    this.canvas.width = 1000;
    this.canvas.height = 600;
    this.context = this.canvas.getContext("2d");
    document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    this.frameNo = 0;
    this.interval = setInterval(updateGameArea, 20);
},

clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}       
}

  var ctx = myGameArea.context;
  var canvas = myGameArea.canvas;

        function DrawingLines(x1, y1, x2, y2, color) {  

            this.x1 = x1;
            this.y1 = y1;
            this.x2 = x2;
            this.y2 = y2;

            this.update = function(){       
                ctx = myGameArea.context;
                ctx.fillStyle = color;
                ctx.lineWidth="2";
                ctx.strokeStyle="black";
                ctx.moveTo(this.x1,this.y1);
                ctx.lineTo(this.x2,this.y2);
                ctx.stroke();   
            }
        }



        function DrawingFixedSquares(x, y, width, height, color) { 
            this.height = height;
            this.width = width;
            this.x = x;
            this.y = y;
            this.update = function(){
                ctx = myGameArea.context;
                ctx.fillStyle = color;
                ctx.fillRect(this.x, this.y, this.width, this.height);
            }   

        }

        function FinalLine(x, y, width, height, color) {  

            this.height = height;
            this.width = width;
            this.x = x;
            this.y = y;
            this.update = function(){
                ctx = myGameArea.context;
                ctx.fillStyle = color;
                ctx.fillRect(this.x, this.y, this.width, this.height);
            }
        }


        function updateGameArea() {

            myGameArea.clear();
            myGameLines1.update();
            myGameLines2.update();
            myGameLines3.update();
            myGameLines4.update();
            myGameLines5.update();
            myGameFinalLine.update();
            myGameFixedSquare1.update();
            myGameFixedSquare2.update();
            myGameFixedSquare3.update();
            myGameFixedSquare4.update();
            myGameFixedSquare5.update();

            YellowTrack.update();
        }


        function animate(YellowTrack, canvas, ctx, startTime) {

            var time = (new Date()).getTime() - startTime;

            var linearSpeed = 100;

            var newY = linearSpeed * time / 1000;

            if(newY < canvas.height) {
              YellowTrack.y = newY;
            }


            ctx.clearRect(0, 0, canvas.width, canvas.height);

              requestAnimFrame(function() {
              animate(YellowTrack, canvas, ctx, startTime);
            });
          }


          setTimeout(function() {
            var startTime = (new Date()).getTime();
            animate(YellowTrack, canvas, ctx, startTime);
          }, 1000);

Upvotes: 0

Views: 152

Answers (1)

Mr. Reddy
Mr. Reddy

Reputation: 1114

Animating things on a canvas is quite easy with window.requestAnimationFrame.

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<style>
			body {
				background-color: black;
			}
			
			canvas {
				position: absolute;
				margin: auto;
				left: 0;
				right: 0;
				border: solid 1px white;
				border-radius: 10px;
			}
		</style>
	</head>
	
	<body>
		<canvas id="canvas"></canvas>
		<script type="application/javascript">
		
		// Anonymous closure to sandbox my code
		void function() {
		
			// Tells the JS engine to use strict syntax rules
			// e.g. creating variables without var, let or const
			// creates an error in strict mode
			"use strict";
			
			var canvasWidth = 180;
			var canvasHeight = 160;
			var canvas = null;
			var ctx = null;
			var mouse = {x: 0.0, y: 0.0};
			var box = {x: 0.0, y: 0.0, width: 20, height: 20};
			var boxMoveSpeed = 25.0;
			
			// Called whenever the mouse moves 
			// (canvas.onmousemove can be used too)
			window.onmousemove = function(e) {
				if (canvas) {
					// Gets the canvas' offset from the top left of the screen
					var boundingRect = canvas.getBoundingClientRect();
					
					mouse.x = e.clientX - boundingRect.left;
					mouse.y = e.clientY - boundingRect.top;
				}
			}
			
			// Game loop
			function loop() {
				// Tick (Update game logic)
				box.x += (mouse.x - box.x - box.width * 0.5) / boxMoveSpeed;
				box.y += (mouse.y - box.y - box.height * 0.5) / boxMoveSpeed;
				
				// Render
				ctx.fillStyle = "#333333";
				ctx.fillRect(0,0,canvasWidth,canvasHeight);
				
				ctx.lineWidth = 3;
				ctx.strokeStyle = "black";
				ctx.fillStyle = "darkred";
				ctx.beginPath();
				ctx.rect(box.x,box.y,box.width,box.height);
				ctx.fill();
				ctx.stroke();
				
				// Handy function that loops this
				// function at 60Hz (60 fps) for me.
				requestAnimationFrame(loop);
			}
			
			// Called when the page finishes loading
			// I treat it like a 'main method' you see
			// in other languages
			window.onload = function() {
				canvas = document.getElementById("canvas");
				canvas.width = canvasWidth;
				canvas.height = canvasHeight;
				
				ctx = canvas.getContext("2d");
				
			loop();
			}
		
		}();
		
		</script>
	</body>
</html>

Upvotes: 1

Related Questions