Canvas not displaying image in JavaScript

I have a bird object with a draw function defined, but for some reason, the image is not showing up when called in the render function. Can someone please help me figure out what I'm doing wrong? Thanks in advance.

EDIT: Upon further investigation, I've discovered that the bird image doesn't always appear because there are other sprites on the screen. When I turn them off, the bird shows up without fail. Is there a solution to this issue?

bird = {
            draw:function() {
                var birdimg = new Image();
                birdimg.onload = function() {
                    ctx.drawImage(birdimg, -20, height - 200);
                }
                birdimg.src = "//i.sstatic.net/nsZLM.png"; //"assets/bird.png";
            }
        };

        function main() {
            canvas = document.createElement("canvas");
            //Set the width and height to the sizes of the browser
            width = window.innerWidth;
            height = window.innerHeight;

            //Frames the game if the width is larger than 500
            if(width >=500){
                width = 320;
                height = 480;
                canvas.style.border = "1px solid #000";
                evt = "mousedown";
            }

            //Sets the canvas sizes to the width and height variables
            canvas.width = width;
            canvas.height = height;
            ctx = canvas.getContext("2d");

            //Set the default state
            currentstate = states.Splash;

            document.body.appendChild(canvas);

            render();
        }

        function render(){
            //Adding bird
            bird.draw();

            //Loads sky.png
            bgimg = new Image();
            bgimg.onload = function() {

                ctx.drawImage(bgimg,-20,height-200);
                ctx.drawImage(bgimg,256,height-200);

            }

            bgimg.src = "assets/sky.png";

            //Loads land img
            landimg = new Image();
            landimg.onload = function() {

                ctx.drawImage(landimg,0,height-100);

            }

            landimg.src = "assets/land.png";

            //Creates rectangle that colors background. THIS IS THE BOTTOM LAYER. WRITE CODE ABOVE

            ctx.fillStyle="#4ec0ca";
            ctx.fillRect(0,0,canvas.width,canvas.height);

            ctx.stroke();
        }

Answer №1

Implementing the suggestions made by @K3N, I have put together a functional example. Many thanks to @K3N for the valuable advice.

After incorporating these modifications, your code will appear as follows:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <script>
    // ensure variables are accessible outside of main()
    var canvas,
        ctx,
        width,
        height;

    var bird = {
        draw: function() {
            var birdimg = new Image();
            birdimg.src ="http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg";

            birdimg.onload = function() {
                ctx.drawImage(birdimg, -20, height - 200);
            };
        }
    };

     function main(){
       canvas = document.createElement("canvas");

       //Adjust dimensions to fit browser window
       width = window.innerWidth;
       height = window.innerHeight;

       //Set game frame if width is over 500
       if(width >=500){
         width = 320;
         height = 480;
         canvas.style.border = "1px solid #000";

         var evt = "mousedown";
       }

       canvas.width = width;
       canvas.height = height;
       ctx = canvas.getContext("2d");

       document.body.appendChild(canvas);

       render();
    }

    main();

    function render(){
      //Include bird in rendering
      bird.draw();
    }
  </script>
</body>
</html>

Live Demo

I trust this explanation proves beneficial, Nick Leoutsakos

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

Can you show me how to recreate a 502 gateway timeout error?

Looking for suggestions on how to create a page that exceeds 600 seconds to load? Any tips on triggering a 502 gateway timeout error would be helpful as well. ...

NextJS 13: Handler Route Request With Invalid JSON Format

Currently utilizing the most recent Next.JS 13 Route Handler to process data submitted by a form. I'm encountering an issue where the new Route Handler isn't working as expected, even though I followed the documentation provided in the link above ...

Why using $refs in interpolation fails and leads to errors in Vue.js 2.x components

Here is a codepen I created: codepen const sidebar = { name: "sidebar", template: "<p>SIDEBAR</p>", data() { return { active: true }; }, methods: { test() { alert("test: " + this.active) } } }; new Vue ...

Utilizing Jquery for precise element placement and retrieving its position details

Within my bundle of jQuery code, there are a few areas where I am experiencing difficulties trying to recall functions. The following is an excerpt of the code: $(document).ready(function(){ $("#myTablePager").html(""); $.ajax({ type: "POS ...

What is the best way to prevent Firefox from storing the data of a textarea in the local environment?

I have been developing a website locally, and I have noticed that there are numerous <textarea> elements present on the site. One issue I am facing is that whenever I reload the site, the content within the <textarea> remains the same. This pe ...

A mysterious issue arose while trying to retrieve the script (Service Worker)

After disconnecting from the internet, my service worker is generating the following error: (unknown) #3016 An unknown error occurred when fetching the script This is what my service worker code looks like: var version = 'v1' this.addEventLis ...

Exploring the process of reading a file from a specified file path within a text area using jQuery

I am looking for a way to dynamically read a file based on its path, and then display the contents of that file in a text area. I have attempted to do this with the following code, but it is not working as expected. Here is the code snippet: goog ...

Tips for coordinating the execution of 2 async.waterfalls in Node.js

I have a series of read commands that need to be executed in sequence. If any of them fail, the processing stops. The array readCommands contains functions for reading... async.waterfall(readCommands, function(err) { if (err) { console.log(e ...

Utilizing Bootstrap's Multi-Grid System

I am currently working on implementing a Bootstrap grid design that resembles pic1.jpg. However, I am facing challenges in achieving the desired layout, as pic2.jpg shows the current scenario. Below, I have shared the code I am using. pic1.jpg :- ! pic2. ...

The PropertyOverrideConfigurer encountered an issue while processing the key 'dataSource' - The key 'dataSource' is invalid, it was expecting 'beanName.property'

During the installation of Sailpoint on Oracle, the configuration properties are as follows: ##### Data Source Properties ##### dataSource.maxWaitMillis=10000 dataSource.maxTotal=50 dataSource.minIdle=5 #dataSource.minEvictableIdleTimeMillis=300000 #dataSo ...

Encountering a build time issue while incorporating Redis into Next.js

Incorporating Redis into my Next.js project has been beneficial overall. However, during the build process (next build), an error arises when it attempts to connect to Redis, resulting in the following message: Collecting page data ..[ioredis] Unhandled e ...

How can I prevent div duplication when working with ui-router?

I created a basic demonstration to get familiar with ui router. Unfortunately, I encountered an issue of duplicated views when utilizing ui router. Below is the snippet of the stateProvider section: app.config(function($stateProvider,$urlRouterProvider) ...

Arranging arrangements in javascript

I am dealing with objects that contain the fields id and position. const items = [{id: 11, position: 1}, {id: 12, position: 2}, {id: 13, position: 3}, {id: 14, position: 4}, {id: 15, position: 5}, {id: 16, position: 6}]; These objects represent folders st ...

Having trouble with request-promise in node.js? It's not functioning as anticipated

Currently utilizing the request-promise node module. Following the documentation closely to ensure correct setup, however encountering the following error: Unhandled rejection StatusCodeError: 400 - "{\n \"error\" : {\n \"s ...

Flexbox causing issues with relative positioning at the bottom of the screen in various browsers

My flex component looks like this: <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" ... width="100%" height="100%" creationComplete="init()"> ....... <components:Naviga ...

What is the equivalent of jQuery's blur event in AngularJS?

I need to implement a functionality in AngularJS where any opened component is closed when clicking outside of it. Is there an existing Angular directive for handling blur events, or do I need to come up with a custom solution? ...

"Error message: Antd datepicker is throwing an error stating that date.clone/date.load is not a

I am working on a React app that has a checkbox to disable a datepicker. However, when I use the checkbox to disable it, I am unable to select any date. If I remove the checkbox and its function, there is no error. Currently, the error message I am getting ...

What could be causing React onclick events to not trigger when wrapped within a Vue application? (No additional libraries)

As I dive into the world of combining React and Vue components, I encountered an interesting challenge... const RootTemplate = () => { return ( <div id="vue-app"> ... <IconButton color="inherit" onClick={thi ...

Checking the boxes in javascript

Hey there, I'm a JavaScript newbie and struggling to validate my check-boxes. Despite looking at multiple examples, the concept is still not sinking in for me. Could someone please provide guidance on how to properly validate my check-boxes? Additiona ...

Encountering an Unexpected Token Import Issue with Page Objects in Webdriver.io and Node.js

Hi, I've encountered an issue while attempting to run my test scripts using Node.JS and Webdriver.io. Everything was functioning correctly until I decided to implement the Page Object Pattern. I am now receiving an error in the console output: ERROR: ...