How to pause the animation - javascript

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>

Related

How can I make a canvas element responsive when resizing the screen?

I have Matrix canvas on my site and there is problem with responsiveness when I change the width of the viewport the canvas doesn't update to fit.
https://codepen.io/ems-sin/pen/zYjpree
HTML
<canvas id="bglitch" ></canvas>
CSS
*{
margin:0;
background-color:#010b13;
overflow: hidden;
}
#bglitch{
opacity: 0.5;
z-index: -10;
top: 0;
right:0;
}
Javascript
var bglitch = document.getElementById("bglitch");
var ctx = bglitch.getContext("2d");
bglitch.height = window.innerHeight;
bglitch.width = window.innerWidth;
var matrix = "アィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽ";
matrix = matrix.split("");
var font_size = 24;
var columns = bglitch.width/font_size;
var drops = [];
for(var x = 0; x < columns; x++)
drops[x] = 1;
function draw()
{
ctx.fillStyle = "rgba(0, 0, 0, 0.04)";
ctx.fillRect(0, 0, bglitch.width, bglitch.height);
ctx.fillStyle = "#f4427d";
ctx.font = font_size + "px arial";
for(var i = 0; i < drops.length; i++){
var text = matrix[Math.floor(Math.random()*matrix.length)];
ctx.fillText(text, i*font_size, drops[i]*font_size);
if(drops[i]*font_size > bglitch.height && Math.random() > 0.975)
drops[i] = 0;
drops[i]++;
}
}
setInterval(draw, 35);
You need to make your code into a function which gets called on the resize event so that the dimensions are updated.
This snippet also clears the current timing interval (if there is one) before starting another one.
<style>
<canvas id="bglitch"></canvas>
</style>
<canvas id="bglitch"></canvas>
<script>
var bglitch = document.getElementById("bglitch");
var ctx = bglitch.getContext("2d");
let timer = '';
function init() {
bglitch.height = window.innerHeight;
bglitch.width = window.innerWidth;
var matrix = "アィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽ";
matrix = matrix.split("");
var font_size = 24;
var columns = bglitch.width / font_size;
var drops = [];
for (var x = 0; x < columns; x++)
drops[x] = 1;
function draw() {
ctx.fillStyle = "rgba(0, 0, 0, 0.04)";
ctx.fillRect(0, 0, bglitch.width, bglitch.height);
ctx.fillStyle = "#f4427d";
ctx.font = font_size + "px arial";
for (var i = 0; i < drops.length; i++) {
var text = matrix[Math.floor(Math.random() * matrix.length)];
ctx.fillText(text, i * font_size, drops[i] * font_size);
if (drops[i] * font_size > bglitch.height && Math.random() > 0.975)
drops[i] = 0;
drops[i]++;
}
}
clearInterval(timer);
timer = setInterval(draw, 35);
}
window.onresize = init;
window.onload = init;
</script>
You need to add resize event listener and recalculate columns accordingly.
Add this at the end of your javascript
window.addEventListener('resize', () => {
bglitch.height = window.innerHeight;
bglitch.width = window.innerWidth;
var columns = bglitch.width/font_size;
for(var x = 0; x < columns; x++) drops[x] = 1;
})
Full working resize
var bglitch = document.getElementById("bglitch");
var ctx = bglitch.getContext("2d");
bglitch.height = window.innerHeight;
bglitch.width = window.innerWidth;
var matrix = "アィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽ";
matrix = matrix.split("");
var font_size = 24;
var columns = bglitch.width/font_size;
var drops = [];
for(var x = 0; x < columns; x++)
drops[x] = 1;
function draw()
{
ctx.fillStyle = "rgba(0, 0, 0, 0.04)";
ctx.fillRect(0, 0, bglitch.width, bglitch.height);
ctx.fillStyle = "#f4427d";
ctx.font = font_size + "px arial";
for(var i = 0; i < drops.length; i++){
var text = matrix[Math.floor(Math.random()*matrix.length)];
ctx.fillText(text, i*font_size, drops[i]*font_size);
if(drops[i]*font_size > bglitch.height && Math.random() > 0.975)
drops[i] = 0;
drops[i]++;
}
}
setInterval(draw, 35);
window.addEventListener('resize', () => {
bglitch.height = window.innerHeight;
bglitch.width = window.innerWidth;
var columns = bglitch.width/font_size;
for(var x = 0; x < columns; x++) drops[x] = 1;
})
*{
margin:0;
background-color:#010b13;
overflow: hidden;
}
#bglitch{
opacity: 0.5;
z-index: -10;
top: 0;
right:0;
}
<canvas id="bglitch" ></canvas>
It's better practice to separate your code into functions. For example init() function that sets all initial variables and run function that will run setTimeout and so on.
let bgData = {
element: undefined,
g: undefined,
matrix: "アィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽ".split(''),
fontSize: 24,
columns: undefined,
drops: [],
};
function init() {
bgData.element = document.getElementById("bglitch");
bgData.g = bgData.element.getContext("2d");
resize();
window.addEventListener('resize', resize)
}
function resize() {
bgData.element.height = window.innerHeight;
bgData.element.width = window.innerWidth;
bgData.columns = bgData.element.width / bgData.fontSize;
for(let x = 0; x < bgData.columns; x++) bgData.drops[x] = 1;
}
function draw() {
bgData.g.fillStyle = "rgba(0, 0, 0, 0.04)";
bgData.g.fillRect(0, 0, bgData.element.width, bgData.element.height);
bgData.g.fillStyle = "#f4427d";
bgData.g.font = bgData.fontSize + "px arial";
for(let i = 0; i < bgData.drops.length; i++) {
const text = bgData.matrix[Math.floor(Math.random()*bgData.matrix.length)];
bgData.g.fillText(text, i * bgData.fontSize, bgData.drops[i] * bgData.fontSize);
if(bgData.drops[i] * bgData.fontSize > bgData.element.height && Math.random() > 0.975) bgData.drops[i] = 0;
bgData.drops[i]++;
}
}
let interval;
function stop() {
clearInterval(interval);
window.removeEventListener('resize', resize)
}
function run() {
stop();
init();
interval = setInterval(draw, 35);
}
run();
*{
margin:0;
background-color:#010b13;
overflow: hidden;
}
#bglitch{
opacity: 0.5;
z-index: -10;
top: 0;
right:0;
}
<canvas id="bglitch" ></canvas>

Inquiry about Undefined array

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

Moving content of canvas with a specific framerate

So I have this sprite animation which goes fine when it's not in movement (I need it to go on 20 fps max because if not the animation would be too fast), but when I try to move it across the screen, the movement looks really choppy. Any ideas on how to make the movement smoothly? Increase the framerate works, but I'd like to see if there is another option aside of that.
var canvasA = document.createElement("canvas");
var canvasB = document.createElement("canvas");
var contextA = canvasA.getContext("2d");
var contextB = canvasB.getContext("2d");
canvasA.style.position = "absolute";
canvasB.style.position = "absolute";
var xpos = 0;
var ypos = 0;
var index = 0;
var frameSizeX = 140;
var frameSizeY = 395;
var numFrames = 20;
var drawing_character = false;
var xPosition = 0;
var now, then, elapsed, startTime, fps, fpsInterval;
var fpscounter = setInterval(updatefps, 1000);
var forw = true;
var cfps = 0;
// Pictures
var background = new Image();
background.src = "http://i.imgur.com/3FDB45h.png";
var character = new Image();
character.src = "http://i.imgur.com/tziJajG.png";
function redraw() {
contextB.clearRect(0, 0, canvasB.width, canvasB.height);
contextB.drawImage(background, 0, 0);
}
function drawchar() { // Input= fps max
requestAnimationFrame(drawchar);
now = Date.now();
elapsed = now - then;
if (elapsed > fpsInterval) {
then = now - (elapsed % fpsInterval);
contextA.clearRect(0, 0, 800, 600);
contextA.drawImage(character,
xpos,
ypos,
frameSizeX,
frameSizeY,
xPosition,
0,
frameSizeX,
frameSizeY);
xpos += frameSizeX;
index += 1;
if (index >= numFrames) {
xpos = 0;
ypos = 0;
index = 0;
} else if (xpos + frameSizeX > character.width) {
xpos = 0;
ypos += frameSizeY;
}
cfps++;
}
}
function updatefps() {
document.getElementById("fps").innerHTML = "FPS: " + cfps;
cfps = 0;
}
function aqui() {
prepareCanvas();
setInterval(redraw, 1000/60);
animarchar(20);
setInterval(move, 1);
}
function move() {
if (forw === true) {
xPosition += 1;
if (xPosition === 300){
forw = false;}
} else {
xPosition -= 1;
if (xPosition === 0){
forw = true;}
}
}
function prepareCanvas() {
canvasB.width = 800;
canvasB.height = 600;
canvasA.width = canvasB.width;
canvasA.height = canvasB.height;
//document.body.appendChild(canvasB);
document.body.appendChild(canvasA);
}
function animarchar(fps) {
fpsInterval = 1000 / fps;
then = Date.now();
startTime = then;
drawchar();
}
window.onload = function () {
aqui();
};
Here is a jsFiddle: https://jsfiddle.net/qb171ghf/

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>

HTML5 drawImage - Not working in Chrome while dragging

Im trying to drag and drop an image in canvas. But when dragging in chrome the image disapears but in Mozilla it works fine. Any help on this would be really appreciated.
HTML File
<head>
<script>
var canvasImages = [];
function imageProp() {
this.imgName = ' ';
this.imgX = 0;
this.imgY = 0;
this.ImgWidth = 1;
this.ImgHeight = 1;
}
function GetFilename(url) {
if (url) {
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1) {
return m[1];
}
}
return "";
}
function load(source) {
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext('2d');
var imageObj = new Image();
//Loading image to Canvas
imageObj.onload = function () {
ctx.drawImage(imageObj, 0, 0);
};
imageObj.src = source;
//Inserting properties of image loaded in canvas to an array
var Property = new imageProp;
//Property.imgName = GetFilename(source);
Property.imgName = source;
Property.imgX = 0;
Property.imgY = 0;
Property.ImgWidth = imageObj.width;
Property.ImgHeight = imageObj.height;
canvasImages.push(Property);
}
</script>
</head>
<body>
<img id = "imgID" onclick=" load(this.src)" src = 'download.png'/>
<canvas id="mycanvas" width="1000" height="1000">HTML5 Not Supported</canvas>
<script src="Canvas_js.js"></script>
</body>
Javascript file
(function () {
"use strict";
/*global document*/
/*global clear*/
/*global canvasImages*/
/*jslint devel: true */
/*jslint browser: true */
var canvas, ctx, ghostcanvas, gctx, RedrawInterval = 20, canvasValid = false, clickLoc = {}, isDragging = false, index = 0, selectedIndex = 0;
clickLoc.x = 0;
clickLoc.y = 0;
function drawCanv() {
var i = 0, imageObj;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (i = 0; i < canvasImages.length; i += 1) {
imageObj = new Image();
imageObj = document.createElement('img');
imageObj.src = canvasImages[i].imgName;
imageObj.onload = function () {
ctx.drawImage(imageObj, canvasImages[i].imgX, canvasImages[i].imgY);
};
}
}
function resizeHandler(index) {
ctx.beginPath();
ctx.strokeRect(canvasImages[index].imgX, canvasImages[index].imgY, canvasImages[index].ImgWidth + 5, canvasImages[index].ImgHeight + 5);
}
function canvasOnClick(e) {
var rect, i = 0;
isDragging = true;
//Get X and Y coordinates of the click
rect = canvas.getBoundingClientRect();
clickLoc.x = e.clientX - rect.left;
clickLoc.y = e.clientY - rect.top;
//Check whether any image is clicked
for (i = 0; i < canvasImages.length; i += 1) {
if (clickLoc.x >= canvasImages[i].imgX && clickLoc.x <= canvasImages[i].imgX + canvasImages[i].ImgWidth && clickLoc.y >= canvasImages[i].imgY && clickLoc.y <= canvasImages[i].imgY + canvasImages[i].ImgHeight) {
selectedIndex = i;
resizeHandler(i);
}
}
}
function canvasMouseUp(e) {
isDragging = false;
}
function canvasMouseMove(e) {
if (isDragging === true) {
canvasImages[selectedIndex].imgX += 5;
drawCanv();
}
}
function init() {
// Defining Canvas and fake canvas
canvas = document.getElementById('mycanvas');
ctx = canvas.getContext('2d');
ghostcanvas = document.createElement('canvas');
ghostcanvas.height = canvas.height;
ghostcanvas.width = canvas.width;
gctx = ghostcanvas.getContext('2d');
// Redrawing canvas for the interval
//setInterval(draw, RedrawInterval);
// Adding Eventlisteners
canvas.addEventListener("mousedown", canvasOnClick, false);
canvas.addEventListener("mouseup", canvasMouseUp, false);
canvas.addEventListener("mousemove", canvasMouseMove, false);
}
init();
}());
Start messing around with
user-select: none;
-webkit-user-select: none;
in your css.

Categories

Resources