How do I make this animation work? - javascript

I wanted a rectangle to move horizontally..However, the rectangle is not animating..How do I fix this?
<script type="text/javascript">
var interval = 10;
var x=0;
var y=0;
var rect = null;
var context ;
var canvas;
function Rectangle(x, y, width, height, borderWidth) {
this.x=x;
this.y=y;
this.width = width;
this.height = height;
this.borderWidth = borderWidth;
}
function DrawRects(){
myRectangle = new Rectangle (250,70,100,50, 5);
context.rect(myRectangle.x,myRectangle.y,myRectangle.width,myRectangle.height)
context.fillStyle="#8ED6FF";
context.fill();
context.lineWidth=myRectangle.borderWidth;
context.strokeStyle="black";
context.stroke();
}
function updateStageObjects() {
var amplitude = 150;
var centerX = 240;
var nextX = myRectangle.x+ 10;
myRectangle.x = nextX;
}
function clearCanvas() {
context.clearRect(0,0,canvas.width, canvas.height);
}
function DrawRect(){
alert("Test1");
setTimeout(CheckCanvas,10);
//clearCanvas();
updateStageObjects();
DrawRects();
alert("Test2");
}
function CheckCanvas(){
return !!(document.createElement('canvas').getContext);
}
function CheckSound(){
return !!(document.createElement('sound').canPlayType)
}
function CheckVideo(){
return !!(document.createElement('video').canPlayType)
}
function Checkstorage(){
return !!(window.localStorage)
}
function CheckVideo(){
return !!(document.createElement('video').canPlayType)
}
function DrawCanvas(){
if (CheckCanvas()){
canvas = document.getElementById('Canvas');
context =canvas.getContext('2d');
$('#Result').text('Canvas supported...');
$('#Result').text($('#Result').text()+'Sound supported...'+CheckSound());
$('#Result').text($('#Result').text()+'Video supported...'+CheckVideo());
$('#Result').text($('#Result').text()+'Storage supported...'+Checkstorage());
DrawRects();
setInterval(DrawRect(), 10);
}
}
</script>
Html:
<canvas id="Canvas" width="800px" height="800px" onclick="DrawCanvas()"> Nor supported</canvas>

You need to do
setInterval(DrawRect, 10);
Using DrawRect() will invoke the function once, and then try to call the result of that function, as a function (which it isn't) every 10 milliseconds.

Related

How can I use clearRect() without erasing other objects I have?

I have a moving object and so it doesn't leave a trail behind I am using the clearRect(). However I can't remove everything in the canvas because that would remove my other object (which is the goal for the player to collect.)
var playerX = 350;
var playerY = 450;
function coin(posX, posY, width, height) {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'gold';
ctx.fillRect(posX, posY, width, height); //this is what I don't want to clear
}
function player() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.fillStyle = "gray";
ctx.fillRect(playerX, playerY, 50, 50);
ctx.closePath();
}
function random(min, max) {
var x = Math.floor(Math.random() * max) + min;
return x;
}
function moveLeft() {
playerX -= 5;
player();
window.requestAnimationFrame(moveLeft);
}
function moveRight() {
playerX += 5;
player();
window.requestAnimationFrame(moveLeft);
}
player();
coin(random(5, 650), random(5, 250), 50, 50);
</script>
Any help would be greatly appreciated.
One thing you can try is make a single animation function that would call itself recursively.
function animate(){
canvas.clearRect()
// draw everything here
window.requestanimationframe(animate)
}
animate()

JS Canvas: How to make rectangle go back and forth once it reaches the boundary

So I have this rectangle that animates across to the right. How can I get the rectangle to reverse it when it hits the boundaries. I'm trying to make it go back and forth.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 50;
var width = 10;
var height = 10;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, y, width, height);
x++;
if(x <= 490) {
setTimeout(animate, 33);
}
}
animate();
}
</script>
</head>
<body>
<canvas id="canvas" width="500" height="400"
style="border: 1px solid #000000;"></canvas>
</body>
</html>
https://codepen.io/forTheLoveOfCode/pen/wqdpeg
Is that what you need? (link to codepen above).
var canvas = document.getElementById("canvas_id");
var context = canvas.getContext('2d');
var x=5;
var y=5;
var velocity = 10;
function move(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
x =x + velocity
if ((x+50)>canvas.width || x<0){
velocity *=-1;
}
draw()
}
function draw(){
context.fillStyle = "#E80C7A";
context.strokeStyle = "#000000";
context.lineWidth = '3';
context.fillRect(x, y, 50, 100);
context.strokeRect(x, y, 50, 100);
}
setInterval(move, 100);
<html>
<body>
<canvas id = "canvas_id">
</canvas>
</body>
</html>
here's a solution with boundaries detection
window.onload=function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 50;
var width = 10;
var height = 10;
var speed = 10; // speed
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, y, width, height);
if(
(x >= 500 - width && speed > 0) || // going to the right and bound reached
(x <= 0 && speed < 0) // going to the left and bound reached
) {
speed *= -1; // inverting the direction
}
x += speed;
setTimeout(animate, 33);
}
animate();
}
<canvas id="canvas" width="500" height="400"
style="border: 1px solid #000000;"></canvas>
consider using requestAnimationFrame instead of setTimeout to do this kind of work.

Animating images with javascript

I am trying to make the images race each other and once one of the images passes the finish line display the winner.
I have some old code I used for the animation but i don't know how to implement the images with it.
<html>
<head>
<title>Canvas Race</title>
<script src="jquery-2.2.3.js"></script>
<style type="text/css">
canvas {
border: 1px solid black;
background-image: url("http://www.gamefromscratch.com/image.axd?picture=road2048v2.png");
background-size: 200px 300px;
background-position-y: -81px;
}
</style>
</head>
<body>
<canvas id="canvas" width="1100" height="150" >
<script>
var blueCar = new Image();
var redCar = new Image();
// images
function image(){
blueCar.src = "http://worldartsme.com/images/car-top-view clipart-1.jpg";
redCar.src = "http://images.clipartpanda.com/car-clipart-top-view-free-vector-red-racing-car-top-view_099252_Red_racing_car_top_view.png";
}
window.onload = function draw(){
var ctx = document.getElementById('canvas').getContext('2d');
ctx.globalCompositeOperation = 'destination-over';
window.requestAnimationFrame(draw);
window.requestAnimationFrame(animate);
// finish line
ctx.beginPath();
ctx.moveTo(1020, 150);
ctx.lineTo(1020, 0);
ctx.strokeStyle = "#FFEF0E";
ctx.stroke();
//blue car
ctx.save();
if(blueCar.complete){
ctx.drawImage(blueCar, 10, 10, 100, 60);
}
// red car
if(redCar.complete){
ctx.drawImage(redCar, 10, 80, 100, 60);
}
}
image();
</script>
</canvas>
<div id="winner"></div>
</body>
</html>
Old code:
I want to use this old code but i don't know what to remove and how to add the images that i have above for the cars. As you can see for this code i created squares instead of images.
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
// drawing red square
function drawRedRect(redCar, ctx) {
ctx.beginPath();
ctx.drawImage(redCar, 5, 5);
}
// finish line
function drawFinishLine(ctx){
ctx.beginPath();
ctx.moveTo(1040, 150);
ctx.lineTo(1040, 0);
ctx.stroke();
}
// this is drawing the blue square
function drawBlueRect(blueRectangle, ctx){
ctx.beginPath();
ctx.rect(blueRectangle.x, blueRectangle.y, blueRectangle.width, blueRectangle.height);
ctx.fillStyle = 'blue';
ctx.fill();
}
// red square animation
function animate(lastTime, redCar, blueRectangle, runAnimation, canvas, ctx) {
if(runAnimation.value) {
// update
var time = (new Date()).getTime();
var timeDiff = time - lastTime;
// pixels / second
var redSpeed = Math.floor((Math.random() * 400) + 1);
var blueSpeed = Math.floor((Math.random() * 400) + 1);
var linearDistEachFrameRed = redSpeed * timeDiff / 1000;
var linearDistEachFrameBlue = blueSpeed * timeDiff / 1000;
var currentX = redRectangle.x;
var currentZ = blueRectangle.x;
if(currentX < canvas.width - redRectangle.width - redRectangle.borderWidth / 2) {
var newX = currentX + linearDistEachFrameRed;
redRectangle.x = newX;
}
if(currentZ < canvas.width - blueRectangle.width - blueRectangle.borderWidth / 2) {
var newZ = currentZ + linearDistEachFrameBlue;
blueRectangle.x = newZ;
}
console.log(redSpeed);
console.log(blueSpeed);
// clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw
drawFinishLine(ctx);
drawRedRect(redRectangle, ctx);
drawBlueRect(blueRectangle, ctx);
//winner(win);
// request new frame
requestAnimFrame(function() {
animate(time, redRectangle, blueRectangle, runAnimation, canvas, ctx);
});
}
}
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var win = document.getElementById('Winner')
//blue square
var blueRectangle = {
x: 5, y: 30, width: 45, height: 25, borderWidth:5
};
//red square
var redRectangle = {
x: 5,
y: 90,
width: 45,
height: 25,
borderWidth: 5
};
/!*
* define the runAnimation boolean as an obect
* so that it can be modified by reference
*!/
var runAnimation = {
value: false
};
// add click listener to canvas
document.getElementById('myCanvas').addEventListener('click', function() {
// flip flag
runAnimation.value = !runAnimation.value;
if(runAnimation.value) {
var date = new Date();
var time = date.getTime();
animate(time, redRectangle, blueRectangle, runAnimation, canvas, ctx);
}
});
drawFinishLine(ctx);
drawRedRect(redRectangle, ctx);
drawBlueRect(blueRectangle, ctx);
//winner(win);
Here is some of your code refactored to race car images:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// game vars
var redRectangle={x:5,y:40,width:62,height:21};
var goldRectangle={x:5,y:75,width:62,height:21};
var finishX=450;
// animation vars
var nextTime=0;
var delay=1000/60;
// image vars and call start() when all images are loaded
var red=new Image();
red.onload=start;
red.src='https://dl.dropboxusercontent.com/u/139992952/multple/car1.png';
var gold=new Image();
gold.onload=start;
gold.src='https://dl.dropboxusercontent.com/u/139992952/multple/car2.png';
var imageCount=2;
function start(){
// return if all the images aren't loaded
if(--imageCount>0){return;}
// start the animation loop
requestAnimationFrame(animate);
}
function animate(time){
// has the desired time elapsed?
if(time<nextTime){requestAnimationFrame(animate);return;}
nextTime=time+delay;
// update the car positions
redRectangle.x+=Math.random()*5;
goldRectangle.x+=Math.random()*5;
// draw the current scene
ctx.clearRect(0,0,canvas.width,canvas.height);
drawFinishLine(ctx);
drawRedRect(redRectangle, ctx);
drawgoldRect(goldRectangle, ctx);
// request another animation loop
hasRedWon=redRectangle.x+redRectangle.width>finishX;
hasGoldWon=goldRectangle.x+goldRectangle.width>finishX;
// alert if race is over
if(hasRedWon){ alert('Red wins'); return; }
if(hasGoldWon){ alert('Gold wins'); return; }
// race is still going, request another animation loop
requestAnimationFrame(animate);
}
// draw images instead of rects
function drawRedRect(redRectangle, ctx){
ctx.drawImage(red, redRectangle.x, redRectangle.y, redRectangle.width, redRectangle.height);
}
// draw images instead of rects
function drawgoldRect(goldRectangle, ctx){
ctx.drawImage(gold, goldRectangle.x, goldRectangle.y, goldRectangle.width, goldRectangle.height);
}
// draw finish line
function drawFinishLine(){
ctx.fillRect(finishX,0,5,ch);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=500 height=300></canvas>

Game loop not doing what its supposed to

Hi I'm trying to make a very simple game using javascripts canvas element. I have a rectangle thats drawn on the canvas and I would like for it to move across the canvas when user clicks a button but its not working.
here is my html:
<style>
canvas {
border: 1px solid black;
height: 300px;
width:500px;
}
</style>
</head>
<body>
<button id = "play">Click to play</button>
</body>
My javascript:
$( document ).ready(function() {
var x = document.createElement("CANVAS");
var ctx = x.getContext("2d");
ctx.fillStyle = "#FF0000";
var x1 = 10;
var y = 10;
ctx.fillRect(x1, y, 80, 10);
document.body.appendChild(x);
var Game = {stopped:true};;
Game.draw = function() {
ctx.fillRect(x1, y, 80, 10);
};
Game.update = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
x1 = x1+5;
};
Game.run = function() {
Game.update();
Game.draw();
};
$("#play").click(function() {
Game.stopped = false;
while (!Game.stopped){
Game.run();
}
});
});
There are multiple problems in your script.
there is no variable called, canvas it is x
Your loop is an infinite while loop, which does not give any time for the UI to update - since browser tab is a single threaded app both js execution and the repaint/refresh of the UI happens in the same thread
So
var interval;
$("#play").click(function () {
Game.stopped = false;
interval = setInterval(Game.run, 5);
});
$("#stop").click(function () {
Game.stopped = true;
clearInterval(interval);
});
Demo: Fiddle
There is another simple implement:
$(document).ready(function () {
var canvas = document.createElement("CANVAS");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
var x1 = 10;
var y = 10;
ctx.fillRect(x1, y, 80, 10);
document.body.appendChild(canvas);
var Game = {stopped: true};
;
Game.draw = function () {
ctx.fillRect(x1, y, 80, 10);
};
Game.update = function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
x1 = x1 + 5;
};
Game.run = function () {
Game.update();
Game.draw();
};
$("#play").click(function () {
Game.stopped = false;
// while (!Game.stopped) {
// Game.run();
// }
if(!Game.stopped){
setInterval(Game.run,1000);
}
});
});
For animation, it's better to use Window.requestAnimationFrame(), if you want to get a better performance.

How do I continuously update these coordinates?

I want to move the rectangle horizontally,however,it enters the updateStageObjects() function several times but does not update the value of myRectangle.x.How do I fix this?
<script type="text/javascript">
var interval = 10;
var x=0;
var y=0;
var myRectangle;
var context ;
var canvas;
function Rectangle(x, y, width, height, borderWidth) {
this.x=x;
this.y=y;
this.width = width;
this.height = height;
this.borderWidth = borderWidth;
}
function DrawRects(){
myRectangle = new Rectangle (250,70,100,50, 5); context.rect(myRectangle.x,myRectangle.y,myRectangle.width,myRectangle.height);
context.fillStyle="#8ED6FF";
context.fill();
context.lineWidth=myRectangle.borderWidth;
context.strokeStyle="black";
context.stroke();
}
function updateStageObjects() {
var amplitude = 150;
var centerX = 240;
myRectangle.x += 100;
alert(myRectangle.x+" "+myRectangle.y);
}
function clearCanvas() {
context.clearRect(0,0,canvas.width, canvas.height);
}
function DrawRect(){
setTimeout(CheckCanvas,10);
clearCanvas();
updateStageObjects();
DrawRects();
}
function CheckCanvas(){
return !!(document.createElement('canvas').getContext);
}
function CheckSound(){
return !!(document.createElement('sound').canPlayType)
}
function CheckVideo(){
return !!(document.createElement('video').canPlayType)
}
function Checkstorage(){
return !!(window.localStorage)
}
function CheckVideo(){
return !!(document.createElement('video').canPlayType)
}
function DrawCanvas(){
if (CheckCanvas()){
canvas = document.getElementById('Canvas');
DrawRects();
setInterval(DrawRect, 10);
}
}
</script>
html
<canvas id="Canvas" width="800px" height="800px" onclick="DrawCanvas()"> Nor supported</canvas>
As Chris has pointed out your DrawRects() always draws the same co-ords, try adding a couple more variables like
var dx = 250;
var dy = 70;
Then change your new Rectangle to
myRectangle = new Rectangle (dx,dy,100,50, 5);
Next change your myRectangle.x += 100 line to
dx += 100;
Hope this helps.
Every time you call updateStageObjects(), it is followed immediately by a call to DrawRects(), which creates a new rectangle at exactly (250,70,100,50, 5). So you'll never notice it increment by 100.
You'll need to pass some numbers back and forth between these functions if you want one of them to remember the changes made in another.

Categories