Stop once condition is reach - javascript

As you can see, i have this code here:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="300"
style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var player = {
x: 0,
y: 297.3
};
var monster = {
x: 150,
y: 296
};
var slope = {
1: {
x: 183,
y: 299
}
}
ctx.font = "13px monospace";
setInterval(function() {
player.x += 8;
ctx.clearRect(0, 0, canvas.width, canvas.height);
}, 50);
setInterval(function() {
ctx.fillText("\\o/",player.x, player.y)
ctx.fillText(">:)",monster.x, monster.y)
ctx.fillText("/",slope[1].x, slope[1].y)
ctx.fillText("_______________________",0,296);
ctx.fillText("_______________________",189,286);
if (player.x >= monster.x - 25) {
monster.x = 1000; monster.y = 1000;
}
if (player.x >= slope[1].x - 21) {
player.y -= 10;
}
}, 50);
</script>
</body>
</html>
I want to stop the player from going up more than 10 (y -= 10 then stop) once it touch the slope instead of keep going up. Is there any solution for this?

You can use a state variable that set false in initial and after action, set true:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="300"
style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var player = {
x: 0,
y: 297.3
};
var monster = {
x: 150,
y: 296
};
var slope = {
1: {
x: 183,
y: 299
}
}
ctx.font = "13px monospace";
setInterval(function() {
player.x += 8;
ctx.clearRect(0, 0, canvas.width, canvas.height);
}, 50);
var up = false;
setInterval(function() {
ctx.fillText("\\o/",player.x, player.y)
ctx.fillText(">:)",monster.x, monster.y)
ctx.fillText("/",slope[1].x, slope[1].y)
ctx.fillText("_______________________",0,296);
ctx.fillText("_______________________",189,286);
if (player.x >= monster.x - 25) {
monster.x = 1000; monster.y = 1000;
}
if (!up && player.x >= slope[1].x - 21) {
player.y -= 10;
up=true
}
}, 50);
</script>
</body>
</html>

Sure, store your interval in a variable, then clear it when you need to :
var myInterval = setInterval(function() {
player.x += 8;
ctx.clearRect(0, 0, canvas.width, canvas.height);
}, 50);
// Whenever you want to stop it
clearInterval(myInterval)

Related

javascript canvas error.... "not defined" for image

I am trying to make the image switch when I press the space bar. but.... when I do I get an error "ig is not defined" Im not sure why its happening any ideas? I should also note that I am using notepad its the free text editor on windows 10 im sure the same code works on mac and linux
Here is the code:
<!DOCTYPE html>
<html>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
var canvas
var ctx
window.onload = function() {
canvas = document.getElementById("gameCanvas")
ctx = canvas.getContext("2d")
ctx.fillStyle = "red"
ctx.fillRect(0, 0, 50, 50)
}
function draw() {
ctx.clearRect(0, 0, 999, 999)
Xpos = Xpos + Xspeed
ctx.fillRect(Xpos, 0, 20, 20)
var ig = new Image()
ig.src = "alien2.png"
var img = new Image();
img.src = "scp.png";
ctx.drawImage(img, Xpos, 145, 50, 50);
}
document.addEventListener("keydown", keyDown)
document.addEventListener("keyup", keyUp)
var Xspeed = 0
var Xpos = 10
setInterval(draw, 50)
function keyUp(evt) {
if (evt.keyCode == 32) Xspeed = 0
ctx.drawImage(ig, 100, 100)
}
function keyDown(evt) {
if (evt.keyCode == 32) Xspeed = 2
ctx.drawImage(ig, 100, 100)
}
</script>
</html>
Move the functions inside the onload event listener so the functions can reference ctx and make ig a global variable:
var canvas
var ctx
window.onload = function() {
canvas = document.getElementById("gameCanvas")
ctx = canvas.getContext("2d")
ctx.fillStyle = "red"
ctx.fillRect(0, 0, 50, 50)
function draw() {
ctx.clearRect(0, 0, 999, 999)
Xpos = Xpos + Xspeed
ctx.fillRect(Xpos, 0, 20, 20)
window.ig = new Image()
ig.src = "https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1";
var img = new Image();
img.src = "https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1";
ctx.drawImage(img, Xpos, 145, 50, 50);
}
document.addEventListener("keydown", keyDown)
document.addEventListener("keyup", keyUp)
var Xspeed = 0
var Xpos = 10
setInterval(draw, 50)
function keyUp(evt) {
if (evt.keyCode == 32) Xspeed = 0
ctx.drawImage(ig, 100, 100)
}
function keyDown(evt) {
if (evt.keyCode == 32) Xspeed = 2
ctx.drawImage(ig, 100, 100)
}
}
<!DOCTYPE html>
<html>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
</body>
</html>

Fade in items individually on a canvas

I would like to animate individual rectangles. I am trying to Fade In a rectangle independently. I want to create FadeIn(rectangle) and FadeOut(Rectangle) functions where I can pass a rectangle to fade in individual items.
I have seen https://codepen.io/mattsrinc/pen/YzPZbWw however, that's having multiple render loops, changing colors,etc. I am trying to make only FadeIn and FadeOut functions.
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"></canvas>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var i = 0;
requestAnimationFrame(test);
requestAnimationFrame(test1);
function test() {
i += 0.002;
i = i < 0 ? 0 : i;
ctx.globalAlpha = 1;
ctx.fillStyle = "white";
ctx.fillRect(20, 20, 75, 50);
ctx.globalAlpha = i;
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 75, 50);
requestAnimationFrame(test);
}
function test1() {
i += 0.002;
i = i < 0 ? 0 : i;
ctx.globalAlpha = 1;
ctx.fillStyle = "white";
ctx.fillRect(100, 60, 75, 50);
ctx.globalAlpha = i;
ctx.fillStyle = "blue";
ctx.fillRect(100, 60, 75, 50);
requestAnimationFrame(test1);
}
You only need one requestAnimationFrame, use clearRect instead of drawing a white rect, clamp the alpha value between 0 and 1 so you won't get weird flickering.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var blueAlpha = 0;
var blueSetp = 0.02; // Blue velocity
var redAlpha = 0;
var redStep = 0.01; // Red velocity
const calmp = (value, min, max) => Math.max(min, Math.min(value, max));
requestAnimationFrame(render);
function render() {
// Setting Blue Alpha
if(blueAlpha < 0 || blueAlpha > 1)
blueSetp = blueSetp * -1; // inverse blue
blueAlpha += blueSetp;
// Drawing Blue
ctx.globalAlpha = calmp(blueAlpha, 0, 1);
ctx.fillStyle = "blue";
ctx.clearRect(100, 60, 75, 50); // Use clearRect
ctx.fillRect(100, 60, 75, 50);
// Setting Red alpha
if(redAlpha < 0 || redAlpha > 1)
redStep = redStep * -1; // inverse red
redAlpha += redStep;
// Drawing Red
ctx.globalAlpha = calmp(redAlpha, 0, 1);
ctx.fillStyle = "red";
ctx.clearRect(20, 20, 75, 50);
ctx.fillRect(20, 20, 75, 50);
requestAnimationFrame(render);
}
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"></canvas>

line contracts and expands in html

i want to make a line that contracts and expands along x-axis randomly it should start from the middle of canvas . I was only able to move the line one way, not both ways! i have the code, if you could please help me i would really appreciate it !
<!DOCTYPE html>
<style>
canvas {
border: solid;
border-color: black; }
</style>
<canvas id="canvas">
</canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "black";
var posX = 0;
var lineLength = 50;
var speed = 2;
function drawLine() {
ctx.beginPath();
ctx.moveTo(posX, 50);
ctx.lineTo(posX + lineLength, 50);
ctx.stroke();
}
function moveLine() {
posX += speed;
if (posX < 0 || posX > canvas.width - 50) {
speed = speed * -1;
}
}
function loop() {
// clear old frame;
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveLine();
drawLine();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
</script>
You want to be modifying the value of lineLength in your loop, not posX. Like this:
function moveLine() {
lineLength += speed;
if (lineLength < 0 || lineLength > canvas.width - 50) {
speed = speed * -1;
}
}
Then you just need to center your line:
function drawLine() {
var center = canvas.width/2;
ctx.beginPath();
ctx.moveTo(center - (lineLength/2), 50);
ctx.lineTo(center + (lineLength/2), 50);
ctx.stroke();
}
Since the X position of your line isn't variable, you don't need posX at all.

Making an object move back and forth in javascript [duplicate]

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.

DrawImage() doesn't draw on canvas

I am trying to make a screen following the player so that the player is in the middle of the screen. I have already made it in another game, but here it doesn't work. Here is my code :
var c = document.getElementById("main");
var ctx = c.getContext("2d");
var screen = document.getElementById("screen").getContext("2d");
var WhatUSeeWidth = document.getElementById("screen").width;
var WhatUSeeHeight = document.getElementById("screen").height;
ctx.beginPath();
for (i = 0; i < 100; i ++) {
if (i % 2) {
ctx.fillStyle = "red";
}
else {
ctx.fillStyle = "blue";
}
ctx.fillRect(0, i * 100, 500, 100);
}
var player = {
x : 700,
y : 800
}
setInterval(tick, 100);
function tick() {
screen.beginPath();
screen.drawImage(c, player.x - WhatUSeeWidth / 2, player.y - WhatUSeeHeight / 2, WhatUSeeWidth, WhatUSeeHeight, 0, 0, WhatUSeeWidth, WhatUSeeHeight);
}
canvas {
border: 2px solid black;
}
<canvas id="main" width="500" height="500"h></canvas>
<canvas id="screen" width="500" height="500"></canvas>
I want to draw The Blue and red canvas in The "screen" canvas Using drawImage
Ok , from your comment I understood what you are looking for. But the problem is that you probably start by an example without having understood. I try to give you my interpretation of what you do , but you should look for a good guide that starts with the basics and deepen animations (for example this: http://www.html5canvastutorials.com/).
HTML
<canvas id="canvasLayer" width="500" height="500"></canvas>
Javascript
var canvas = document.getElementById("canvasLayer");
var context = canvas.getContext("2d");
var WhatUSeeWidth = document.getElementById("canvasLayer").width;
var WhatUSeeHeight = document.getElementById("canvasLayer").height;
var player = {
x : 0,
y : 0
}
function drawBackground() {
for (i = 0; i < 100; i ++) {
if (i % 2) {
context.fillStyle = "red";
}
else {
context.fillStyle = "blue";
}
context.fillRect(0, i * 100, 500, 100);
}
}
function playerMove() {
context.beginPath();
var radius = 5;
context.arc(player.x, player.y, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 1;
context.strokeStyle = '#003300';
context.stroke();
}
setInterval(tick, 100);
function tick() {
context.clearRect(0, 0, canvas.width, canvas.height);
drawBackground();
player.x++;
player.y++;
playerMove();
}
This is the JSFiddle.
EDIT WITH THE CORRECT ANSWER
The error is in the position of the object "player". It is located outside of the canvas, width:500 height:500 and the "player" is in position x:700 y:800.
Changing the position of the player your copy will appear.
var player = {
x : 50,
y : 50
}
Here the jsfiddle example.

Categories

Resources