What could be causing the image to not show up?

I recently created this HTML code and tested it, expecting an image to be displayed:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Gamedev Canvas Workshop</title>

</head>
<body>

<canvas id="myCanvas" width="500" height="500"></canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var heroRadius = 20;
var heroX = 50;
var heroY = 50;
var upPressed = false;
var downPressed = false;
var leftPressed = false;
var rightPressed = false;
var heroSpeed = 2;

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

function keyDownHandler(e) {
if(e.keyCode == 87) {
    upPressed = true;
}
else if(e.keyCode == 83) {
    downPressed = true;
}
else if(e.keyCode == 65){
    leftPressed = true;
}
else if(e.keyCode == 68){
    rightPressed = true;
}
}

function keyUpHandler(e) {
if(e.keyCode == 87) {
    upPressed = false;
}
else if(e.keyCode == 83) {
    downPressed = false;
}
else if(e.keyCode == 65) {
    leftPressed = false;
}
else if(e.keyCode = 68) {
    rightPressed = false;
}
}

function drawHero() {
  var imageObj = new Image();

  imageObj.onload = function() {
    ctx.drawImage(imageObj, 69, 100);
  };
  imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
}

function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawHero();

requestAnimationFrame(draw);
}
draw();
</script>

</body>
</html>

Unfortunately, the image is not appearing as intended. I was trying to create a game using an image for practice. The image shows up without requestAnimationFrame removed, but I require it for future movement implementation. Can anyone help me figure out why the image isn't displaying? Thank you!

Answer №1

Looking at this snippet

function drawHero() {
  var imageObj = new Image();

  imageObj.onload = function() {
    ctx.drawImage(imageObj, 69, 100);
  };
  imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
}

A better approach would be to avoid waiting for onload in every frame. Instead, create an init function and bind it to the body's onload event. Within this function, set a class level variable with the image source of Darth Vader.

var imageObj = new Image();
function init(){
   imageObj.src='http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
}

Then in your drawing loop, you can simplify it like this:

function drawHero() {  
    ctx.drawImage(imageObj, 69, 100);  
}

The canvas doesn't require the image to be fully loaded before drawing, so no need for an onload event here.

Furthermore, as you progress, consider avoiding direct drawing on the display canvas. Instead, draw on a hidden canvas first and then transfer the final result to the display canvas for improved performance.

Answer №2

The reason your image is not showing up is because you forgot to call the load method of your Image object. You only defined what should happen when a specific event occurs (in this case, loading).

Below is the correct code snippet:

function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
imageObject.load();

requestAnimationFrame(render);
}

It would be beneficial for you to consider the advice provided by other developers regarding your project's architecture.

Answer №3

Your code is running into an issue where the draw function is being called multiple times per second, causing your canvas to be cleared before the image can show up. This is due to calling `requestAnimationFrame(draw)` within the draw function itself. If you're new to working with canvas, this can be a common pitfall. For more information on `requestAnimationFrame`, check out the documentation here. To learn about `clearRect` and how it affects your canvas, visit this link. I made a small revision to your code in this Jsfiddle by commenting out the problematic line. You might also want to follow the approach suggested by Trevor D if you want to maintain your background image without interference. Good luck!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to turn off _moz_resizing on my browser?

I am currently using the nicEdit editor and have successfully integrated my own custom image resizing script. However, I am facing an issue where the default _moz_resizing feature in Firefox is interfering with my custom script. My goal is to have specifi ...

Generating a multidimensional associative array based on user inputs from a form

What is the best way to transform form input data into a multidimensional associative array? This is how the form appears: <div id="items"> <h4>Engraving Text</h4> <div class="item" data-position="1"> <h4 id="en ...

the modal body is taking longer than expected to load with ajax

I have a unique modal that I'm filling with dynamic data through an Ajax GET request upon modal load. Interestingly, the data is not fetched or added to the modal body unless I trigger an alert first. The structure of my modal is as follows: <div ...

Delay the execution of a JavaScript function by a few seconds

<script type="text/javascript"> var timeout; function doAjaxFunc(){ alert("called"); $.ajax({ type: "POST", url: "searchSuggest.php", data: dataString, cache: fal ...

What is the best way to determine the total number of rows in a JSON file?

Here is the JSON data I have: [0:{name:"jason",height:"150cm"}, 1:{name:"henry",height:"178cm"}] In my function, I am attempting to create a for loop like this: function DrawTable(output) { var ...

In an AngularJS application, when using fullPage.js on the homepage, it is recommended to ensure that it is

Within my angularJs application, I have implemented fullPage.js on the homepage exclusively to ensure no interference with other pages or routes. To make this possible, I am currently triggering a destroy action during the locationChangeSuccess event. I a ...

angular express cycle without end

I'm experiencing an issue with my express/angular app where the index page is causing an infinite loop. Here's how I have set up my app: app.configure(function() { // setting up our express application app.use(express.logger('dev& ...

What is the best way to display a Bootstrap toggle?

I am facing an issue with a Bootstrap toggle in a Handlebars template. When the page initially loads, the toggle is visible, however, after re-templating the Handlebars template that contains the toggle, it disappears. Before Re-Template: Initial code : ...

What is the best method to extract the values of objects in an array that share

var data= [{tharea: "Rare Disease", value: 3405220}, {tharea: "Rare Disease", value: 1108620}, {tharea: "Rare Disease", value: 9964980}, {tharea: "Rare Disease", value: 3881360}, ...

Independent Dropbox Collections

Query: function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var colCount = table.rows[0].cells.length; for (var i = 0; i < colCount; i++) { var ...

Remove an owl carousel using Laravel, Vue.js, and Axios

I've implemented a sleek slider on my website to showcase images with accompanying text to visitors. The slider utilizes owl carousel within a vue component and is functioning properly. Now, I'm attempting to add a delete button so that users who ...

Using an external JavaScript script may encounter difficulties when loading pages with jQuery

Trying to utilize jQuery for loading html posts into the main html page and enabling external scripts to function on them. Utilizing a script (load.js) to load posts into the index.html page: $(document).ready(function () { $('#header').loa ...

How can I make my iPad switch to landscape mode in my specific situation?

I'm attempting to trigger the landscape mode on an iPad web browser, including the address bar and tabs, when a user clicks a link. Here's what I currently have: <div> <a ng-click="click me()" href="www.cnn.com">Click me</a&g ...

Performing functions in JavaScript/jQuery

I have a function that retrieves a user's latitude and longitude. I need this information to generate a URL based on the user's location, which will vary. The generated URL is then used in an AJAX call. However, the second AJAX call is being trig ...

Implementing pagination links to trigger image changes on click

I have a javascript function that swaps the image source when clicked. I am looking to incorporate pagination links in this script. Specifically, I want to include "Previous" and "Next" text links to navigate between images. Can someone help me figure out ...

Discovering local establishments using mongoDB and mongoose

I am managing a small database where I manually added places and currently working on filtering them by minDistance and maxDistance. Here is the mongoose schema I am using: var schema = new Schema({ name: { type: String, unique: fals ...

Tips for triggering the API call only when a change is detected

#In the provided code snippet, the useEffect hook is being used to fetch data from an API using the apiData() function. The data retrieved consists of objects with properties such as id, name, parent name, and isActive. The isActive property is linked to ...

Flickity: There was an error due to the inability to read the property 'querySelectorAll' of null

I've spent hours debugging my JavaScript code, but I can't seem to get rid of this error. Did I overlook something or add incorrect code? The error message reads: consultationSlider.js:9 Uncaught TypeError: cellsButtons.querySelectorAll is not a ...

AngularJS is throwing a $injector:modulerr error and I've exhausted all possible solutions

I recently started learning Angular and I've been following the tutorial on the official AngularJS website. Here's what I've tried so far: Installed angular-route and included the script below angular.min.js Utilized ngRoute in my mod ...

Adjust the language code in a URL using JavaScript or Node.js

Within my common header file, there is a navbar that includes a multilanguage dropdown menu. The issue I am facing is that when I select a language from the dropdown, the page translates correctly. However, when I navigate to other pages, the selected lang ...