Reputation: 4051
I have tried countless times to make my background appear in javascript as I was hoping if anyone was able to help shred some light onto why it will not load anything.
I have edited and changed this countless times today and still can't make it work.
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.height = 512;
ctx.width = 480;
document.body.appendChild(canvas);
// Game Loop
var Time;
function gameLoop() {
var now = date.now();
var dateTime = (now - time) / 1000.0;
update(dateTime);
render();
time = now;
requestAnimationFrame(gameLoop);
}
// image call
function backgroundDraw() {
backgroundImg = new image;
backgroundImg.src = 'images/background.png'
backgroundImg.onload = function () {
ctx.drawImage(backgroundImg, 100, 100);
}
}
backgroundDraw();
I am new to javascript and The guides I'm looking at to work with are http://jlongster.com/Making-Sprite-based-Games-with-Canvas and http://www.w3schools.com/tags/canvas_drawimage.asp
Any help would really be appreciated guys!
Upvotes: 0
Views: 107
Reputation: 27
var canvas = document.createElement("canvas");
canvas.style.width = "480px"; // missing width
canvas.style.height = "512px"; // missing height
var ctx = canvas.getContext("2d");
ctx.height = 512;
ctx.width = 480;
document.body.appendChild(canvas);
// Game Loop
var Time;
function gameLoop() {
var now = Date.now();
var dateTime = (now - time) / 1000.0;
update(dateTime);
render();
time = now;
requestAnimationFrame(gameLoop);
}
// image call
function backgroundDraw() {
backgroundImg = new Image; // construct typo
backgroundImg.src = 'http://www.artisticadigital.com/wp-content/uploads/cache/2014/02/HTML5_Logo_512/14550496.png'
backgroundImg.onload = function () {
ctx.drawImage(backgroundImg, 100, 100);
}
}
backgroundDraw();
I don't understand that you want to do
Upvotes: 0
Reputation: 668
A couple of things. First var Time !== time
in your gameLoop function. Also, you'll want to define your onload function before setting the src on your image element. new image
needs image to be capitalized: new Image
. For now I'd comment out your gameLoop since you're just trying to display the image. Doing that and changing image to Image got the image to render for me.
Upvotes: 0
Reputation: 30098
The first problem is setting up the dimension of the canvas. Use the canvas element to set its width and height.
Change this
ctx.height = 512;
ctx.width = 480;
to this
canvas.height = 512;
canvas.width = 480;
Your image instantiation has a typo, change
backgroundImg = new image;
to
backgroundImg = new Image;
you can check this fiddle for the working demo.
Upvotes: 1