DbD Posted December 29, 2014 Share Posted December 29, 2014 I can't seem to get this image that i'm loading into my game to work. My movement worked perfectly before when I was just using a rectangle that I drew in myself, but now that I switched to using actual graphics, It won't work. Can anyone help me? Heres the code:<!DOCTYPE html><head> <link rel="stylesheet" href="test.css"> <script type="text/javascript"> function preloader() { var img = new Image(); img.src = "dude.png"; img.onload = function() { context.drawImage(img, x, y); context.beginPath(); } } </script> </head><body onLoad="preloader()"> <h3>The real deal: </h3> <canvas id="square" width=800 height=600></canvas> <h4>The testing area: </h4> <br> <canvas id="circle" width=100 height=100></canvas> <script> // Get first canvas element and its context var canvas = document.getElementById("square"); var context = canvas.getContext("2d"); var x = 400, y = 300, velY = 0, velX = 0, speed = 2, friction = 0.78, keys = []; function update() { if (keys[87]) { if (velY > -speed) { velY--; } } if (keys[83]) { if (velY < speed) { velY++; } } if (keys[68]) { if (velX < speed) { velX++; } } if (keys[65]) { if (velX > -speed) { velX--; } } velY *= friction; y += velY; velX *= friction; x += velX; if (x >= 790) { x = 790; } else if (x <= 0) { x = 0; } if (y > 590) { y = 590; } else if (y <= 0) { y = 0; } // Draw something in the canvas context.clearRect(0, 0, 800, 600); context.beginPath(); context.drawImage(img,x,y); context.fill(); setTimeout(update, 10);} update(); document.body.addEventListener("keydown", function (e) { keys[e.keyCode] = true; }); document.body.addEventListener("keyup", function (e) { keys[e.keyCode] = false; }); </script> </body></html>Thanks! Quote Link to comment Share on other sites More sharing options...
msha Posted December 29, 2014 Share Posted December 29, 2014 Hit F12 or CTR+SHIFT+I in your browser(any modern browser) and you'll see Developer Tools window - collection of extremely helpful stuff for debugging your code.In this case, if you looked at Console tab of the Developer Tools, you'd see "Uncaught ReferenceError: img is not defined index.html:91" and realize that the code on line 91 can not see variable img.function preloader() { var img = new Image();img variable will only be visible inside this function.context.drawImage(img,x,y); <- img is not visible here. I will work this way:var img = new Image();function preloader() { ... .... Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.