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

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>

Related

Image won't load in javascript canvas

I am trying to load an image... it's in the same folder and I'm not getting any errors as far as I know everything should be fine... I'm not quite sure what's wrong... if you have any ideas let me know in the comments! thanks for helping!
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)
var img = new Image();
img.src = "scp.png";
ctx.drawImage(img, 145, 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
}
function keyDown(evt) {
if (evt.keyCode == 32) Xspeed = 2
}
function draw() {
ctx.clearRect(0, 0, 999, 999)
Xpos = Xpos + Xspeed
ctx.fillRect(Xpos, 0, 20, 20)
}
</script>
</html>
It appears that you are constantly drawing over the picture in the draw() function. You can add the
var img = new Image();
img.src = "img_the_scream.jpg";
ctx.drawImage(img, 145, 145, 50, 50);
into the draw function which will show to image and the square.

How to move an object in canvas with arrows?

Someone please can help me with an object moving automatically when I click on the right arrow in canvas.
My code is
if(e.keyCode == 39) {
bullet.x = +5;
setTimeout(function() {
ctx.clearRect(0,0,canvas.width,canvas.height)
ctx.drawImage(player.Image, player.x, player.y , player.width, player.height);
ctx.drawImage(bullet.Image , bullet.x , bullet.y , bullet.width , bullet.height);
}, 300);
console.log("DOWN");
}
What do I need to add for the object moving by the right arrow?
It is necessary to use ClearReact to advance with the function setInterval ()
let canvas = document.getElementById("mycanvas");
let ctx = canvas.getContext('2d');
juego();
let ev;
let x = 0;
let base_image = new Image();
base_image.src = 'https://img.icons8.com/pastel-glyph/2x/search.png';
window.onkeydown = function(e) {
this.ev = e;
}
function draw() {
if (typeof this.ev != 'undefined' && this.ev.keyCode == 39) {
x = x + 10;
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(base_image, x, 10);
}
}
function juego() {
pat = ctx.createPattern(canvas, "repeat");
window.setInterval(draw, 500);
}
canvas {
outline: black 3px solid;
}
<canvas id="mycanvas" width="150" height="150"></canvas>
for try press left arrow

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.

Stop once condition is reach

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)

How would I put this code together?

I have a Javascript program working in three different places: here,
here, and here.
But I don't know how would I put them in one file. This is where I am at right now.
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<style>
body {
background-color:#E4E0FF;
}
#canvas {
border:10px solid red;
background-color:white;
}
#canvas2 {
border:10px solid red;
background-color:white;
}
#canvas3 {
border:10px solid red;
background-color:white;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="300">
</canvas>
<canvas id="canvas2" width="400" height="300">
</canvas>
<canvas id="canvas3" width="400" height="300">
</canvas>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script type="text/javascript">
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
var toggle=0;
var x=150;
var y=100;
var w=100;
var h=100;
var r=60;
var wasInside=false;
ctx.fillStyle = "#000000";
ctx.fillRect(x, y, w, h);
function changeColor() {
if (toggle == 0) {
ctx.fillStyle = "#04B45F";
toggle = 1;
} else if (toggle ==1){
ctx.fillStyle = "#04B45F";
toggle = 2;
}else if (toggle == 2){
ctx.fillStyle = "#0000FF";
toggle = 3;
}else if (toggle == 3){
ctx.fillStyle == "#190707";
toggle = 4;
}else if (toggle == 4){
ctx.fillStyle = "#210B61";
toggle = 5;
}else if (toggle == 5){
ctx.fillStyle = "#FA58AC";
toggle = 6;
}else if (toggle ==6){
ctx.fillStyle = "#FFFF00";
toggle = 7;
}else{
ctx.fillStyle = "#F5A9D0";
toggle = 0;
}
ctx.fillRect(x, y, w, h);
}
function changeRadius() {
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0,0, 400, 300);
r = Math.floor((Math.random() * 80) + 20);
ctx.beginPath();
ctx.arc(200, 150, r, 0, 2 * Math.PI);
ctx.stroke();
}
function changeWidth() {
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0,0, 400, 300);
width = Math.floor((Math.random()*50)+1);
ctx.lineWidth=width;
ctx.stroke();
}
function handleMouseMove(e) {
var mx = parseInt(e.clientX - offsetX);
var my = parseInt(e.clientY - offsetY);
var isInsideNow = (mx > x && mx < x + w && my > y && my <= y + h);
if (isInsideNow && !wasInside) {
changeColor();
wasInside = true;
} else if (!isInsideNow && wasInside) {
wasInside = false;
}
}
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvas2").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvas3").mousemove(function (e) {
handleMouseMove(e);
});
</script>
</body>
</html>
So, how would I tell the program to do circle thing in 2nd canvas and line in 3rd canvas???
I haven't called the changeWidth and changeRadius functions yet, because it'll just do it in the first canvas making a mess.
I just need something in this part of the code to call different functions in different canvas's
if (isInsideNow && !wasInside) {
changeColor();
wasInside = true;
} else if (!isInsideNow && wasInside) {
wasInside = false;
}
I'm not a canvas expert, but just for giving you an idea, check this FIDDLE
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
inspect these 2 lines, the context ctx wil draw in the canvas with id=canvas. you can create other contex variables to draw in the other canvas or reuse the same.
updated FIDDLE
Update for the update: FIDDLE

Categories

Resources