HTML5 Canvas with Javascript , Image loading - javascript

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Web Game </title>
</head>
<body onkeydown="keyDown(event)" onkeyup="keyUp(event)"></body>
<canvas id="gameCanvas1" width=600 height=400 style ="position:absoloute:top:0;left:0;background-image:url('img/background.jpg')">
Please upgrade your browser to support HTML5.<br/>
One recommendation is to install the latest Chrome or Firefox.
</canvas>
<script>
gamecanvas = document.getElementById("gamecanvas1");
ctx=gamecanvas.getContext("2d");
var img = new Image();
img.src = "img/left.png";
//MainLoop
MainLoop();
function MainLoop(){
grafx.drawImage(img,0,0)};
setTimeout(MainLoop, 1000/60); //about 60fps
}
</script>
</html>
I am trying to load the left.png image. I am making a basic platformer in HTML and JavaScript, but the image isn't being shown. I think the drawImage is being called before the image is loaded but I'm not sure how to fix it. Thanks.

There are two problems I found.
P1:
grafx.drawImage(img,0,0)}; is wrong
it should be
ctx.drawImage(img,0,0);
P2:
use image onload callback rather than setTimeout.
img.onload = function () {
ctx.drawImage(img,0,0);
};

You have several errors in your js code.
your element has an id of gameCanvas1, but you are trying to get an element with an id of gamecanvas1 (document.getElementById("gamecanvas1");)
So the javascript wont find your canvas, which means the image wont be drawn. You also have an extra closing } which is causing errors in your function
Try opening your browsers dev console, you'll see the issues

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Web Game </title>
</head>
<body onkeydown="keyDown(event)" onkeyup="keyUp(event)"></body>
<canvas id="gameCanvas1" width=600 height=400 style ="position:absoloute:top:0;left:0;background-image:url('img/background.jpg')">
Please upgrade your browser to support HTML5.<br/>
One recommendation is to install the latest Chrome or Firefox.
</canvas>
<script>
console.log("i am here ");
var gamecanvas = document.getElementById('gameCanvas1');
var ctx=gamecanvas.getContext('2d');
var img = new Image();
img.src = "img/left.png";
//MainLoop
MainLoop();
function MainLoop(){
ctx.drawImage(img, 10, 10);
setTimeout(function(){
MainLoop();
}, 1000/60); //about 60fps
}
</script>
</html>

Related

GetContext() is not working

I'm using regular JS (I know it isn't the best, but I'm a beginner)
So I'm writing code for a canvas project. However when using the getContext() function the JS console says
Uncaught TypeError: canvas.getContext is not a function
at master.js:4
I've looked around and found that nothing has fixed my problem.
var canvas = document.getElementsByClassName('myCanvas');
console.log(canvas);
var context = canvas.getContext('2d');
console.log(context);
The HTML is this:
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="master.js" charset="utf-8"></script>
<link rel="stylesheet" href="master.css">
</head>
<body>
<canvas class="myCanvas">Your browser doesn't support HTML canvas</canvas>
</body>
</html>
Does anyone know what I am doing wrong?
getElementsByClassName returns an array of elements. Thus, it does not have the method you are looking for. Try the following:
var canvas = document.getElementsByClassName('myCanvas')[0];
console.log(canvas);
var context = canvas.getContext('2d');
console.log(context);
Your code is also stored in the HTML head, so your canvas element will not be found. Either put your <script> tag in the HTML <body> tag or set a function inside document.onload as follows:
document.onload = function() {
var canvas = document.getElementsByClassName('myCanvas')[0];
console.log(canvas);
var context = canvas.getContext('2d');
console.log(context);
}

Load image using Javascript?

Here's the current code of my HTML page:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
<meta name="robots" content="noindex, nofollow">
<meta http-equiv="refresh" content="3;URL='http://google.com'" />
</head>
<body>
<script>
var image = document.images[0];
var downloadingImage = new Image();
downloadingImage.onload = function(){
image.src = this.src;
};
downloadingImage.src = "http://example.com/pixel";
</script>
<script>
window.location = "http://google.com";
</script>
</body>
</html>
This part of the code should be using Javascript to load an image:
var image = document.images[0];
var downloadingImage = new Image();
downloadingImage.onload = function(){
image.src = this.src;
};
downloadingImage.src = "http://example.com/pixel";
This is being done to verify is a user has javascript enabled or not. We direct visitors to specific advertisers and certain ones require that Javascript be enabled. The pixel that's being loaded is so we can track fraudulent traffic from third-party vendors that try to send millions of bot hits using stuff like curl.
The amount of users with javascript enabled is slightly lower than I expected and I'm not trying to debate the amount. But does anyone see anything wrong with this code?
It's my understanding that javascript loads in order, so the image should be loaded in a browser before the user is redirected, correct? And do you see anything wrong in the code that I guess would cause it to not load in certain browsers?
While the script is executed in order, the loading of images is non-blocking. As a result, setting the image.src to something does not wait for that image to load before moving on. You need to determine when you'd like to be redirected, and place that code inside the image's onload function. Try this:
Wrap your refresh tag in <noscript></noscript> (only valid for html5)
Modify your code to this:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
<meta name="robots" content="noindex, nofollow">
<noscript>
<meta http-equiv="refresh" content="3;URL='http://google.com'" />
</noscript>
</head>
<body>
<img src="//example.org/pixel1">
<script>
var image = document.images[0];
var downloadingImage = new Image();
downloadingImage.onload = function(){
console.log('downloadImage loaded');
image.onload = function(){
console.log('image loaded');
window.location = "http://google.com";
}
image.src = this.src;
};
downloadingImage.src = "//example.com/pixel2";
</script>
</body>
</html>

How to link JavaScript frameworks/extensions in HTML?

I have seen a lot of frameworks and extensions recently and all for a lot of different things. It is hard for me to do things using just raw JavaScript or raw jQuery. I want to use these JS extensions/frameworks but the problem is that I don't know how to link them to my HTML document.
For Example: <script src="some link of fw/ext" type="text/javascript"></script> I put this in the <head> of my HTML and then write my code in a different file named "script.js" (made using notepad) but the code doesn't seem to work.
I know this is a problem because I don't link it properly.
I want to work with fabric.js on a project related to HTML5 canvas. I think I need to link both, my code and the framework in some way but I'm not sure as to how should I do it.
My HTML code :
<!DOCTYPE html>
<html>
<head>
<title>Code Example</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script type="text/javscript" src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
</head>
<body>
<canvas id="draw" width="250px" height="250px">This if browser doesn't support HTML5
</canvas>
</body>
</html>
My JS Code:
var canvas = new fabric.Canvas('draw');
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.width = 100;
canvas.freeDrawingBrush.color = "#ff0000";
Should work somewhat like this : http://jsfiddle.net/MartinThoma/B525t/5/
You need to load fabric.js first at the header and then you need to load your js file order matters.
<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js'></script>
<script type='text/javascript' src='yourjsfile.js'></script
In case you are not clear on how to add elements to the canvas. Then here is one snippet which could help you.
Also wrap your code inside onload() function so that when the script loads, the #draw element is available
window.onload = function() {
var canvas = new fabric.Canvas('draw');
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.width = 5;
canvas.freeDrawingBrush.color = "#ff0000";
// create a rectangle object
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 20,
height: 20
});
// you need to add the object to canvas
canvas.add(rect);
}

Canvas won't appear in browser

My canvas wont show in my browser.
I'm guessing the reason is because of some newbie jquery mistakes.
The codes below are in two separate folders, Game.html and game.js
Game.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<canvas id="gameCanvas">
</canvas>
<script src="Scripts/jquery-2.0.3.js" type="text/javascript"> </script>
<script src="Scripts/game.js" type="text/javascript"> </script>
</body>
</html>
game.js:
var canvasWidth = 800;
var canvasHeight = 600;
$('#gameCanvas').attr('width', canvasWidth);
$('#gameCanvas').attr('height', canvasHeight);
var canvas = $('#gameCanvas')[0].getContext('2d');
canvas.strokeRect(0, 0, canvasWidth, canvasHeight);
Here is tested your code is working perfectly.
Look in your Scripts folder content files jquery-2.0.3.js and game.js.
the only possibility is error path, look at this.
And what browser are you testing? html5 canvas is then only works in some new browsers.
checked here if your browser does have canvas support
Code Equals
working example here
Are you sure your reference to the script file is correct. If both html and script are in two different folders, then the reference might need to be:
<script src="../Scripts/jquery-2.0.3.js" type="text/javascript"> </script>
<script src="../Scripts/game.js" type="text/javascript"> </script>

DOM Not Loading In Chrome App

I have a simple HTML5 Snake game that uses canvas that I want to package as a Chrome App. Here is my normal HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Snake</title>
<link rel="stylesheet" href="snake.css">
</head>
<body>
<canvas id="canvas" width="700" height="700"></canvas>
<script type="text/javascript" src="food.js"></script>
<script type="text/javascript" src="snake.js"></script>
<script type="text/javascript" src="point.js"></script>
<script type="text/javascript" src="game.js"></script>
<script type="text/javascript">
window.onload = function() {
var canvas = document.getElementById("canvas"),
game = new Game(canvas, new Snake(canvas), new Food(canvas));
game.init();
game.run();
}
</script>
</body>
</html>
However the script in the HTML is not allowed. So I removed it and placed it main.js which creates the window. I provide a callback that is the same as window.onload above because my understanding is that this is the chrome app equivalent:
chrome.app.runtime.onLaunched.addListener(function() {
"use strict";
chrome.app.window.create('snake.html', {
bounds: {
width: 800,
height: 800
}
}, function() {
var canvas = document.getElementById("canvas"),
game = new Game(canvas, new Snake(canvas), new Food(canvas));
game.init();
game.run();
});
});
This runs after the DOM appears to have loaded but document.getElementById always returns null. Looking at the document in the developer tools it looks like only the scripts are loaded even though I can see the canvas in the app window (I have a border around the canvas). Can anyone tell me what is going on? Where is the appropriate place to access the DOM from when window.onload doesn't work?
main.js is running on the background / event page and is not in the same context as the newly created window's DOM. You can interact with that context as documented on the create callback, but it's not how I recommend solving this.
Instead, from your main.js simply create the window, and from the HTML file load script code that executes directly.
window.html:
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="700" height="700"></canvas>
<script ...</script>
<script type="text/javascript" src="window.js"></script>
window.js:
var canvas = document.getElementById("canvas"),
game = new Game(canvas, new Snake(canvas), new Food(canvas));
game.init();
game.run();

Categories