Inquiry about Undefined array - javascript

As I have revised on the codes, I have found that the code that I wrote cannot function normally but the words shown are always “undefined”, but I have checked many times that the code seems perfect. Could you mind to have a look and check for me? That really confused me a lot...Thank you very much. I appreciate your help very much.
<!DOCTYPE html>
<html>
<head>
<style>
body{display:block;
margin:auto;
text-align:center;}
canvas{border:1px solid black;}
</style>
<script>
var canvas;
var ctx;
var timer;
var words=["canoe","buddha","elephant","dice"];//
var words=["canoe","buddha","elephant","dice"];
var answerIndex=-1;
var answer_x=-1;
var answer_y=-1;
var plate_x=-1;
var plate_y=-1;
var score=0;
function draw()
{ ctx.clearRect(0,0,canvas.width,canvas.height-10);
//canvas=document.getElementById("Canvas");
//ctx=canvas.getcontext("2d")
answer_x+=3;
answer_y+=3;
var answer=words[answerIndex];
ctx.font="20px Arial";
ctx.fillStyle="black";
ctx.fillText(answer,answer_x,answer_y);
var distance=answer_x-plate_x;
document.getElementById("plate_x").innerHTML=plate_x;
document.getElementById("word_x").innerHTML=answer_x;
document.getElementById("dist").innerHTML=distance;
if (answer_y>=plate_y)
{
clearInterval(timer);
if ((distance<50) && (distance>-50))
{
document.getElementById("message").innerHTML="Bravo!";
score++;
document.getElementById("score").innerHTML=score;
}
else
{
document.getElementById("message").innerHTML="Game over!";
}
}
}
function getRandomIndex()
{var random_number=Math.random*words.length;
var random_int=Math.floor(random_number);
return random_int;
}
function play()
{
canvas=document.getElementById("Canvas");
ctx=canvas.getContext("2d");
answerIndex = getRandomIndex();
var answer = words[answerIndex];
var imageFileName = answer + ".jpg";
document.getElementById("myPic").src = imageFileName;
answer_x=0;
answer_y=0;
ctx.clearRect(0,0,canvas.width,canvas.height);
plate_x=0;
plate_y=canvas.height-10;
ctx.fillStyle="blue";
ctx.fillRect(plate_x,plate_y,50,10);
clearInterval(timer);
timer=setInterval("draw()",100);
}
function moveleft()
{ ctx.clearRect(plate_x,plate_y,50,10);
if(plate_x>0)
{plate_x-=20;}
ctx.fillStyle="blue";
ctx.fillRect(plate_x,plate_y,50,10);
}
function moveright()
{ ctx.clearRect(plate_x,plate_y,50,10);
if(plate_x<(canvas.width-50))
{plate_x+=20;}
ctx.fillStyle="blue";
ctx.fillRect(plate_x,plate_y,50,10);
}
</script>
</head>
<body>
<h1>Catch the word!</h1>
<img id="myPic" alt="no pic" src="" width="200"/><br/>
<canvas id="Canvas" width="300" height="250"></canvas>
<br/><button onclick="play()">Play</button>
<button onclick="moveleft()">←</button>
<button onclick="moveright()">→</button>
<p id="message">Move to catch the word!</p>
<p id="score"></p>
<p>Plate X-coordinate:</p><p id="plate_x"></p>
<p>Word X-coordinate:</p><p id="word_x"></p>
<p>Distance:</p><p id="dist"></p>
</body>
</html>

In your getRandomIndex() function, you forgot the parenthesis after Math.random, which accesses random as a property rather than a method. So Math.random in your formula should be Math.random() instead.
Your current code doesn't work because your getRandomIndex() function returns NaN:
function getRandomIndex() {
var random_number = Math.random * words.length;
var random_int = Math.floor(random_number);
console.log(Math.random);
// ƒ random() { [native code] }
console.log(random_number);
// NaN
console.log(random_int);
// NaN
return random_int;
}
If you change your current code to use Math.random() instead, then your getRandomIndex() function will return the random integer value you are expecting:
function getRandomIndex() {
var random_number = Math.random() * words.length; // changed code
var random_int = Math.floor(random_number);
console.log(Math.random());
// 0.40108128192401526 (of course this value will change each time)
console.log(random_number);
// 3.613675793700807 (of course this value will change each time)
console.log(random_int);
// 3 (of course this value will change each time)
return random_int;
}
To follow on the comment from #David, in the future if you run into something like this you could always console.log() some of the values from the function that is not returning the expected output. This will help you run down your issue when there are no errors in the console.

Your variable ctx is undefined because you define ctx in the function play().
and at the beginning of your script you are declaring all your variables but you leave ctx and canvas empty
var canvas; //<------ You leave canvas empty
var ctx; //<------ You leave ctx empty
var timer;
var words = ["canoe", "buddha", "elephant", "dice"];
var words = ["canoe", "buddha", "elephant", "dice"];
var answerIndex = -1;
var answer_x = -1;
var answer_y = -1;
var plate_x = -1;
var plate_y = -1;
var score = 0;
At the play function you assign a value to it.
function play() {
canvas = document.getElementById("Canvas");
ctx = canvas.getContext("2d"); //<---- Here you add a value
answerIndex = getRandomIndex();
var answer = words[answerIndex];
var imageFileName = answer + ".jpg";
document.getElementById("myPic").src = imageFileName;
answer_x = 0;
answer_y = 0;
ctx.clearRect(0, 0, canvas.width, canvas.height);
plate_x = 0;
plate_y = canvas.height - 10;
ctx.fillStyle = "blue";
ctx.fillRect(plate_x, plate_y, 50, 10);
clearInterval(timer);
timer = setInterval("draw()", 100);
}
But that value will only be available within that function.
and all your other functions also use ctx!
In the folowing code block I clarified all the places where it went wrong and where it didn't go wrong.
var canvas;
var ctx; //<--- here you leave it empty
var timer;
var words = ["canoe", "buddha", "elephant", "dice"];
var words = ["canoe", "buddha", "elephant", "dice"];
var answerIndex = -1;
var answer_x = -1;
var answer_y = -1;
var plate_x = -1;
var plate_y = -1;
var score = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height - 10); //<--- Here you are calling ctx but ctx is not defined!
//canvas=document.getElementById("Canvas");
//ctx=canvas.getcontext("2d") //Here you are randomly identifying ctx but you made a comment of it...
answer_x += 3;
answer_y += 3;
var answer = words[answerIndex];
ctx.font = "20px Arial"; //<--- Here you are calling ctx but ctx is not defined!
ctx.fillStyle = "black"; //<--- Here you are calling ctx but ctx is not defined!
ctx.fillText(answer, answer_x, answer_y); //<--- Here you are calling ctx but ctx is not defined!
var distance = answer_x - plate_x;
document.getElementById("plate_x").innerHTML = plate_x;
document.getElementById("word_x").innerHTML = answer_x;
document.getElementById("dist").innerHTML = distance;
if (answer_y >= plate_y) {
clearInterval(timer);
if ((distance < 50) && (distance > -50)) {
document.getElementById("message").innerHTML = "Bravo!";
score++;
document.getElementById("score").innerHTML = score;
} else {
document.getElementById("message").innerHTML = "Game over!";
}
}
}
function getRandomIndex() {
var random_number = Math.random * words.length;
var random_int = Math.floor(random_number);
return random_int;
}
function play() {
canvas = document.getElementById("Canvas");
ctx = canvas.getContext("2d"); // <--- here you correctly identified ctx
answerIndex = getRandomIndex();
var answer = words[answerIndex];
var imageFileName = answer + ".jpg";
document.getElementById("myPic").src = imageFileName;
answer_x = 0;
answer_y = 0;
ctx.clearRect(0, 0, canvas.width, canvas.height); //<---- So this can be executed and is NOT undefined
plate_x = 0;
plate_y = canvas.height - 10;
ctx.fillStyle = "blue"; //<---- So this can be executed and is NOT undefined
ctx.fillRect(plate_x, plate_y, 50, 10); //<---- So this can be executed and is NOT undefined
clearInterval(timer);
timer = setInterval("draw()", 100);
}
function moveleft() {
ctx.clearRect(plate_x, plate_y, 50, 10); //<--- Here you are calling ctx but ctx is not defined!
if (plate_x > 0) {
plate_x -= 20;
}
ctx.fillStyle = "blue"; //<--- Here you are calling ctx but ctx is not defined!
ctx.fillRect(plate_x, plate_y, 50, 10); //<--- Here you are calling ctx but ctx is not defined!
}
function moveright() {
ctx.clearRect(plate_x, plate_y, 50, 10); //<--- Here you are calling ctx but ctx is not defined!
if (plate_x < (canvas.width - 50)) {
plate_x += 20;
}
ctx.fillStyle = "blue"; //<--- Here you are calling ctx but ctx is not defined!
ctx.fillRect(plate_x, plate_y, 50, 10); //<--- Here you are calling ctx but ctx is not defined!
}
SO the solution will be to declare ctx and canvas at the beginning like this:
var canvas = document.getElementById("Canvas"); //<----- Like this
var ctx = canvas.getContext("2d"); //<------ Like this
var timer;
var words = ["canoe", "buddha", "elephant", "dice"];
var words = ["canoe", "buddha", "elephant", "dice"];
var answerIndex = -1;
var answer_x = -1;
var answer_y = -1;
var plate_x = -1;
var plate_y = -1;
var score = 0;
But in order for this to work you will need the remove the script from the head and place it all the way to the bottom of your body like this:
<html>
<head>
Remove your script from here
</head>
<body>
All the contents of your body
And place your script here
</body>
</html>
or declare ctx at the beginning of every function that needs it like this:
var canvas;
var ctx;
var timer;
var words = ["canoe", "buddha", "elephant", "dice"];
var words = ["canoe", "buddha", "elephant", "dice"];
var answerIndex = -1;
var answer_x = -1;
var answer_y = -1;
var plate_x = -1;
var plate_y = -1;
var score = 0;
function draw() {
canvas = document.getElementById("Canvas"); //<----- declare canvas here
ctx = canvas.getcontext("2d"); // <--- declare ctx here
ctx.clearRect(0, 0, canvas.width, canvas.height - 10);
answer_x += 3;
answer_y += 3;
var answer = words[answerIndex];
ctx.font = "20px Arial";
ctx.fillStyle = "black";
ctx.fillText(answer, answer_x, answer_y);
var distance = answer_x - plate_x;
document.getElementById("plate_x").innerHTML = plate_x;
document.getElementById("word_x").innerHTML = answer_x;
document.getElementById("dist").innerHTML = distance;
if (answer_y >= plate_y) {
clearInterval(timer);
if ((distance < 50) && (distance > -50)) {
document.getElementById("message").innerHTML = "Bravo!";
score++;
document.getElementById("score").innerHTML = score;
} else {
document.getElementById("message").innerHTML = "Game over!";
}
}
}
function getRandomIndex() {
var random_number = Math.random * words.length;
var random_int = Math.floor(random_number);
return random_int;
}
function play() {
canvas = document.getElementById("Canvas"); //<----- declare canvas here
ctx = canvas.getcontext("2d"); // <--- declare ctx here
answerIndex = getRandomIndex();
var answer = words[answerIndex];
var imageFileName = answer + ".jpg";
document.getElementById("myPic").src = imageFileName;
answer_x = 0;
answer_y = 0;
ctx.clearRect(0, 0, canvas.width, canvas.height);
plate_x = 0;
plate_y = canvas.height - 10;
ctx.fillStyle = "blue";
ctx.fillRect(plate_x, plate_y, 50, 10);
clearInterval(timer);
timer = setInterval("draw()", 100);
}
function moveleft() {
canvas = document.getElementById("Canvas"); //<----- declare canvas here
ctx = canvas.getcontext("2d"); // <--- declare ctx here
ctx.clearRect(plate_x, plate_y, 50, 10);
if (plate_x > 0) {
plate_x -= 20;
}
ctx.fillStyle = "blue";
ctx.fillRect(plate_x, plate_y, 50, 10);
}
function moveright() {
canvas = document.getElementById("Canvas"); //<----- declare canvas here
ctx = canvas.getcontext("2d"); // <--- declare ctx here
ctx.clearRect(plate_x, plate_y, 50, 10);
if (plate_x < (canvas.width - 50)) {
plate_x += 20;
}
ctx.fillStyle = "blue";
ctx.fillRect(plate_x, plate_y, 50, 10);
}
Also please read the comments of other people too because they might note other mistakes that I didn't see

Related

How to move the canvas backward in javascript?

I try to think how the box can move backward when it hit 1000px (canvas.width) ,but I don’t know how it solves after If condition, so there’s my script, anyone can help me ?
var canvas = document.querySelector("canvas");
var canvasCT = canvas.getContext("2d");
var x = 50;
function draw() {
canvas.width = canvas.width;
canvasCT.fillStyle = "blue";
canvasCT.fillRect(x, 50, 100, 100);
}
function run() {
draw();
x += 5 ;
if (x > 1000) {
......
}
}
setInterval(run, 10);
var canvas = document.querySelector("canvas");
var canvasCT = canvas.getContext("2d");
var x = 50;
var speed = 5;
function draw() {
canvas.width = canvas.width;
canvasCT.fillStyle = "blue";
canvasCT.fillRect(x, 50, 100, 100);
}
function run() {
draw();
x += speed;
if (x > 1000 || x < 0) {
speed = -speed;
}
}
setInterval(run, 10);
<canvas width=1000></canvas>

How to pause the animation

I make this image move around the canvas but none of the methods stop it from moving.I make the setInterval to make the move and clear the Interval later by clearInterval in order to stop the motion but seems it won't work
<html>
<head>
<script type="application/javascript">
var ctx = null;
var x_icon = 0;
var y_icon = 0;
var stepX = 1;
var stepY = 1;
var size_x = 221;
var size_y = 184;
var canvas_size_x = 800;
var canvas_size_y = 600;
var anim_img = null;
function draw() {
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
anim_img = new Image(size_x, size_y);
anim_img.onload = function() {
var myvar = setInterval(myAnimation, 10);
function stopMove() {
clearInterval(myVar);
}
}
anim_img.src = 'image/download.jpg';
}
function myAnimation() {
ctx.clearRect(0, 0, canvas_size_x, canvas_size_y);
if (x_icon < 0 || x_icon > canvas_size_x - size_x) {stepX = -stepX; }
if (y_icon < 0 || y_icon > canvas_size_y - size_y) {stepY = -stepY; }
x_icon += stepX;
y_icon += stepY;
ctx.drawImage(anim_img, x_icon, y_icon);
}
</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="800" height="600" style="border:solid 1px;"></canvas>
<button onmousedown="stopMove()">STOP</button>
</body>
</html>
I expected to stop the motion of the download.jpg on click of the STOP button but it won't work
As #Snel23 said, you need to lift stopMove() and myvar out from the draw() context.
var ctx = null;
var x_icon = 0;
var y_icon = 0;
var stepX = 1;
var stepY = 1;
var size_x = 221;
var size_y = 184;
var canvas_size_x = 800;
var canvas_size_y = 600;
var anim_img = null;
var myvar = null; // moving interval handle outside draw()
function draw() {
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
anim_img = new Image(size_x, size_y);
anim_img.onload = function()
{
myvar = setInterval(myAnimation, 10);
}
anim_img.src = 'image/download.jpg';
}
function stopMove() {
clearInterval(myVar);
}
function myAnimation() {
ctx.clearRect(0, 0, canvas_size_x, canvas_size_y);
if (x_icon < 0 || x_icon > canvas_size_x - size_x) {stepX = -stepX; }
if (y_icon < 0 || y_icon > canvas_size_y - size_y) {stepY = -stepY; }
x_icon += stepX;
y_icon += stepY;
ctx.drawImage(anim_img, x_icon, y_icon);
}
If you declare your interval (which you call myVar) at the top level of your code (outside of your functions) and also move your nested function out to the top level, you can access both of them as needed, something like:
// Defines global identifiers
let
ctx = null,
x_icon = 0,
y_icon = 0,
stepX = 1,
stepY = 1,
size_x = 260,
size_y = 175,
canvas_size_x = 400,
canvas_size_y = 180,
anim_img = null,
interval = null; // `interval` is a global variable
const
canvas = document.getElementById("canvas"),
button = document.getElementById("button");
// Calls `stop` when the user clicks the button
button.addEventListener("click", stop);
// Calls `draw` immediately to render the initial canvas
draw();
function draw() {
ctx = canvas.getContext("2d");
anim_img = new Image(size_x, size_y);
anim_img.onload = function() {
// Calls `animate` repeatedly until `interval` is cleared
interval = setInterval(animate, 30);
}
anim_img.src = 'https://www.logomaker.com/wp-content/uploads/2018/12/education1.png';
}
function stop() {
clearInterval(interval);
}
function animate() {
// Re-draws the image at different positions on the canvas
ctx.clearRect(0, 0, canvas_size_x, canvas_size_y);
if (x_icon < 0 || x_icon > canvas_size_x - size_x) { stepX *= -1; }
if (y_icon < 0 || y_icon > canvas_size_y - size_y) { stepY *= -1; }
x_icon += stepX;
y_icon += stepY;
ctx.drawImage(anim_img, x_icon, y_icon);
}
<canvas id="canvas" width="400" height="180" style="border:solid 1px;"></canvas>
<button id="button">STOP</button>

Adding objects into array

Could someone tell me what's wrong with this code ? I am trying to fill canvas with squares as objects but as the loop is done and i am trying to draw that square on canvas nothing happens...
var canvas = document.getElementById('c');
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(35, 180, 218)";
var rectHeight = 5;
var rectWidth = 5;
var cells = [];
for (var i = 0; i <= canvas.width/rectWidth; i++) {
for (var x = 0; x <= canvas.height/rectHeight; x++) {
cells[i] = {
posX : i*rectWidth,
posY : x*rectHeight,
draw : function() {
ctx.fillRect(posX, posY, rectWidth, rectHeight);
},
clear : function() {
ctx.clearRect(posX, posY, rectWidth, rectHeight);
}
};
}
}
cells[2].draw;
var canvas = document.getElementById('c');
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
var rectHeight = 15;
var rectWidth = 15;
var cells = [];
for (var i = 0; i <= canvas.width/rectWidth; i++) {
for (var x = 0; x <= canvas.height/rectHeight; x++) {
cells[i] = {
posX : i*rectWidth,
posY : x*rectHeight,
draw : function() {
ctx.fillRect(this.posX, this.posY, rectWidth, rectHeight);
},
clear : function() {
ctx.clearRect(positionX, positionY, rectWidth, rectHeight);
}
};
}
}
cells[2].draw();
<canvas id="c" width="500" height="400"></canvas>
Thanks for the help #Xufox #SimranjitSingh and #Andreas..
Code now works like this:
var canvas = document.getElementById('c');
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(35, 180, 218)";
var rectHeight = 5;
var rectWidth = 5;
var cells = [];
for (var i = 0; i <= canvas.width/rectWidth; i++) {
for (var x = 0; x <= canvas.height/rectHeight; x++) {
cells[i*x] = {
posX : i*rectWidth,
posY : x*rectHeight,
draw : function() {
ctx.fillRect(this.posX, this.posY, rectWidth, rectHeight);
},
clear : function() {
ctx.clearRect(this.posX, this.posY, rectWidth, rectHeight);
}
};
}
}
cells[2].draw();

Why is my line not drawing over time?

I am trying to have a line draw to the canvas over a certain amount of time(ten seconds to be exact). I'm able to see that the script is counting to a certain time and then stopping, but I'm not seeing the line being drawn. Can anyone show me what I'm doing wrong?
$(document).ready(function(){
canvas = document.getElementById("test");
ctx = canvas.getContext("2d");
var count = 0;
var start_x = 0;
var start_y = 100;
var end_x = 50;
var end_y = 100;
var counter = setInterval(countNumbers, 1000);
ctx.beginPath();
ctx.moveTo(start_x, start_y);
console.log("Start");
function countNumbers(){
count += 1;
ctx.lineTo((start_x + count), start_y);
console.log(count);
if((start_x == end_x) || (count == 10)){
clearInterval(counter);
console.log("End");
}
}
ctx.lineWidth = 5;
ctx.strokeStyle = "white";
ctx.stroke();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="test"></canvas>
Try to move stroke inside the Interval. Because in your case stroke are called immediately without lineTo data. And after that lineTo are called in interval function and cannot be rendered without stroke.
$(document).ready(function(){
canvas = document.getElementById("test");
ctx = canvas.getContext("2d");
var count = 0;
var start_x = 0;
var start_y = 100;
var end_x = 50;
var end_y = 100;
var counter = setInterval(countNumbers, 1000);
ctx.beginPath();
ctx.moveTo(start_x, start_y);
console.log("Start");
function countNumbers(){
count += 1;
ctx.lineTo((start_x + count), start_y);
console.log(count);
if((start_x == end_x) || (count == 10)){
clearInterval(counter);
console.log("End");
ctx.lineWidth = 5; // <----- move here
ctx.strokeStyle = "white";
ctx.stroke();
}
}
})
Also ensure that you are not drawing white lines on white background
$(document).ready(function(){
canvas = document.getElementById("test");
ctx = canvas.getContext("2d");
var count = 0;
var start_x = 0;
var start_y = 100;
var end_x = 50;
var end_y = 100;
var counter = setInterval(countNumbers, 1000);
ctx.beginPath();
ctx.moveTo(start_x, start_y);
console.log("Start");
ctx.lineWidth = 5;
ctx.strokeStyle = "black";
function countNumbers(){
count += 1;
ctx.lineTo((start_x + count), start_y);
ctx.stroke();
console.log(count);
if((start_x == end_x) || (count == 10)){
clearInterval(counter);
console.log("End");
ctx.strokeStyle = "white";
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="test"></canvas>
I would count down for the step. This will allow you to figure out the step.
I modified your code to allow you to pass parameters into the interval function to minimize global scope variables. Since I passed a reference of the interval into itself, you no longer need to have global variables.
I created two function, the first will create a path and then stroke it. The second one will stroke a sub-line after each tick of the interval. I added a simple check for even-odd to swap between colors.
$(document).ready(function() {
var canvas = $('canvas#test')[0];
var ctx = canvas.getContext('2d');
var count = 10;
var start_x = 50, start_y = 50;
var end_x = 250, end_y = 150;
var delta_x = end_x - start_x, delta_y = end_y - start_y;
var step_x = delta_x / count, step_y = delta_y / count;
canvas.width = 300;
canvas.height = 200;
// Fill canvas with solid black.
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'black';
ctx.fill();
// Kick off the line stroke timer. No more global variables!
var counter = setInterval(function(opts) {
// Pass a reference to the timer into the interval.
strokeLineTimerLive(counter, opts);
}, 500, {
ctx : ctx,
n : count,
x1 : start_x,
y1 : start_y,
x2 : end_x,
y2 : end_y,
dx : step_x,
dy : step_y,
});
// After the interval has ended, the path is finally stroked.
function strokeLineTimer(timer, opts) {
if (!opts.init) {
console.log("Start");
opts.ctx.beginPath();
opts.ctx.moveTo(opts.x1, opts.y1);
opts.ctx.lineWidth = 5;
opts.ctx.strokeStyle = 'white';
opts.init = true;
}
opts.n -= 1;
opts.ctx.lineTo((opts.x1 += opts.dx), (opts.y1 += opts.dy));
console.log(opts.n);
if ((opts.x1 == opts.x2) || (opts.n == 0)){
clearInterval(timer);
opts.ctx.stroke();
console.log("End");
}
}
// After each tick of the interval, a line is stroked.
function strokeLineTimerLive(timer, opts) {
if (!opts.init) {
console.log("Start");
opts.ctx.beginPath();
opts.ctx.moveTo(opts.x1, opts.y1);
opts.ctx.lineWidth = 5;
opts.init = true;
}
opts.n -= 1;
opts.ctx.strokeStyle = opts.n % 2 == 0 ? 'white' : 'red';
opts.ctx.lineTo((opts.x1 += opts.dx), (opts.y1 += opts.dy));
opts.ctx.stroke();
console.log(opts.n);
if ((opts.x1 == opts.x2) || (opts.n == 0)){
clearInterval(timer);
console.log("End");
} else {
opts.ctx.beginPath();
opts.ctx.moveTo(opts.x1, opts.y1);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="test"></canvas>

How to make the objects fall in javascript?

I am trying to make this game, you should not collide the falling object. I have the objects falling and I have my black square, but it flashes when I run it and Im not sure how to make the code stop when the two objects collide together.
here is the code that I have so far!
<html>
<body>
<canvas id="canvasRegn" width="600" height="450"style="margin:100px;"></canvas>
<script>
var ctx;
var imgBg;
var imgDrops;
var noOfDrops = 50;
var fallingDrops = [];
function drawBackground(){
ctx.drawImage(imgBg, 0, 0); //Background
}
function draw() {
drawBackground();
for (var i=0; i< noOfDrops; i++)
{
ctx.drawImage (fallingDrops[i].image, fallingDrops[i].x, fallingDrops[i].y); //The rain drop
fallingDrops[i].y += fallingDrops[i].speed; //Set the falling speed
if (fallingDrops[i].y > 480) { //Repeat the raindrop when it falls out of view
fallingDrops[i].y = -25 //Account for the image size
fallingDrops[i].x = Math.random() * 800; //Make it appear randomly along the width
}
}
}
function setup() {
var canvas = document.getElementById('canvasRegn');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
imgBg = new Image();
imgBg.src = "http://www.hamdancommunications.com/HComm/img/wite%20square.png";
setInterval(draw, 36);
for (var i = 0; i < noOfDrops; i++) {
var fallingDr = new Object();
fallingDr["image"] = new Image();
fallingDr.image.src = 'http://s18.postimg.org/o6jpmdf9x/Line1.jpg';
fallingDr["x"] = Math.random() * 800;
fallingDr["y"] = Math.random() * 5;
fallingDr["speed"] = 3 + Math.random() * 5;
fallingDrops.push(fallingDr);
anotherGame();
}
}
}
setup();
function anotherGame(){
var canvas = document.getElementById("canvasRegn");
var ctx = canvas.getContext('2d');
canvas.addEventListener("mousedown", clicked);
canvas.addEventListener("mousemove", moved);
canvas.addEventListener("mouseup", released);
var isclicked = 0;
var square = new Object();
square.color = "black";
square.x = 100;
square.y = 100;
square.w = 50;
square.h = 50;
var offX = 0;
var offY = 0;
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = square.color;
ctx.fillRect(square.x,square.y,square.w,square.h);
}
function game(){
}
function clicked(e){
var x = e.offsetX;
var y = e.offsetY;
if(x >= square.x && x <= square.x + square.w &&
y >= square.y && y <= square.y + square.h){
isclicked = 1;
offX = x - square.x;
offY = y - square.y;
}
}
function moved(e){
if(isclicked == 1){
var x = e.offsetX;
var y = e.offsetY;
square.x = x - offX;
square.y = y - offY;
}
}
function released(e){
var x = e.offsetX;
var y = e.offsetY;
isclicked = 0;
}
var drawtimer = setInterval(draw, 1000/30);
var gametimer = setInterval(game, 1000/10);
}
</script>
</body>
</html>

Categories

Resources