Image drawn to HTML5 Canvas does not display correctly on first load

Asked
Active3 hr before
Viewed126 times

8 Answers

html5displayimage
90%

The circle is probably not showing up because you are drawing it before the image is loaded. Change your last statement to:,The reason it works after you hit refresh is because the image is now pre-loaded into the cache.,You always want to wait for any images to load before you attempt to draw them or nothing will show up on the canvas instead., Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers

The circle is probably not showing up because you are drawing it before the image is loaded. Change your last statement to:

// Lets not init until the image is actually done loading
topMap.onload = function() {
   init();
}
88%

drawImage asks for 9 parameters, first of which is image. We looked and understood that canvas requires a preloaded image to draw and not just a URI to the image. Why does it need that? It will become clear as you read.,For a refresher, here are the 9 parameters that drawImage accepts.,To draw the selected portion of the image, we again need four parameters.,The error is telling us that it needs an image element and not just a URI to the image. To get around that, this is what we can do.

image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight
load more v
72%

The drawPlayer method is called by drawActors, which is responsible for drawing all the actors in the game.,Think of a way to allow us to draw an inverted character without loading additional image files and without having to make transformed drawImage calls every frame.,The syncState method first computes a new viewport and then draws the game scene at the appropriate position.,We don’t bother waiting for the sprite image to load. Calling drawImage with an image that hasn’t been loaded yet will simply do nothing. Thus, we might fail to draw the game properly for the first few frames, while the image is still loading, but that is not a serious problem. Since we keep updating the screen, the correct scene will appear as soon as the loading finishes.

The angle of this line is currentAngle + 0.5 * sliceAngle. The following code finds a position on this line 120 pixels from the center:

let middleAngle = currentAngle + 0.5 * sliceAngle;
let textX = Math.cos(middleAngle) * 120 + centerX;
let textY = Math.sin(middleAngle) * 120 + centerY;
65%

The basic HTML5 Canvas API includes a 2D context that allows a programmer to draw various shapes, render text, and display images directly onto a defined area of the browser window. You can apply colors; rotations; alpha transparencies; pixel manipulations; and various types of lines, curves, boxes, and fills to augment the shapes, text, and images you place onto the canvas.,We will delve into writing text, graphics, and images to HTML5 Canvas in later chapters, so for now, we will only spend a very short time on the code of the drawScreen() function.,It’s time to create actual Canvas API code. Every operation we perform on Canvas will be through the context object, as it references the object on the HTML page.,Finally, we need to get a reference to the 2D context so we can manipulate it. HTML5 Canvas is designed to work with multiple contexts, including a proposed 3D context. However, for the purposes of this book, we only need to get the 2D context:

<!doctype html>
<html lang="en">

<head>
   <meta charset="UTF-8">
   <title>CH1EX1: Basic Hello World HTML Page</title>
</head>

<body>
   Hello World!
</body>

</html>
load more v
75%

In the first method, I’ll use JavaScript image() object to load an image and initialize the object with the image source. This is one of the simplest ways to dynamically add an image to your web page and I’ll use this technique to add the image to the canvas element.,Must read Space Animation on HTML5 canvas and JavaScript for beginners,Also read: How to Pass Multiple Image References to a User Defined Function in JavaScript,Read this: Do you know how to rotate and save an image using canvas?

<html>
<head>
    <title>Add Image to Canvas Using image() Object</title>
</head>
<body>
    <canvas id="canvas">
        Sorry. Your browser does not support HTML5 canvas element.
    </canvas>
</body>

<script>
    window.onload = function () {

        // GET THE IMAGE.
        var img = new Image();
        img.src = '../../images/hawa-mahal.jpg';

        // WAIT TILL IMAGE IS LOADED.
        img.onload = function () {
            fill_canvas(img);       // FILL THE CANVAS WITH THE IMAGE.
        }

        function fill_canvas(img) {
            // CREATE CANVAS CONTEXT.
            var canvas = document.getElementById('canvas');
            var ctx = canvas.getContext('2d');

            canvas.width = img.width;
            canvas.height = img.height;

            ctx.drawImage(img, 0, 0);       // DRAW THE IMAGE TO THE CANVAS.
        }
    }
</script>
</html>
load more v
40%

Make sure your image object is fully loaded before you try to draw it on the canvas with context.drawImage. Otherwise the image will silently fail to display.,Example making sure the image is fully loaded before trying to draw it with .drawImage,Example loading multiple images before trying to draw with any of them,There are more full-functioned image loaders, but this example illustrates how to do it

Example making sure the image is fully loaded before trying to draw it with .drawImage

var img = new Image();
img.onload = start;
img.onerror = function() {
   alert(img.src + ' failed');
}
img.src = "someImage.png";

function start() {
   // start() is called AFTER the image is fully loaded regardless 
   //     of start's position in the code
}
load more v
22%

In this article we will explore how to draw Images onto a Canvas.,We will start with a simple example and then explore some issues you might encounter. We’ll look at how to load the image from various sources, how to display the image on “retina” displays without bluriness, and at some compatibility and performance problems.,drawing images onto canvas,Here is the javascript that will draw the image on to the canvas.

A simple html layout with both the image and the canvas already loaded as DOM elements in our page.

<!DOCTYPE html>
<html>

<head>
   <title>Image drawing</title>
   <script type="text/javascript" src="draw.js"></script>
</head>

<body>
   <img id="html5" src="http://www.w3.org/html/logo/img/mark-word-icon.png" />
</body>

</html>
load more v
60%

With the following code we load up an image and display it at the center of the canvas. In the HTML we specify the canvas, and the image that we are going to display:,Next up in our HTML5 for Mobile Web series is the canvas element. Canvas is particularly interesting since it facilitates the use of graphics without the need for any plugins or other technologies other than JavaScript and CSS., Canvas element not supported. Here is picture of a cute kitten instead ,We can scale the image too with this function, if we provide width and height parameters:

This creates a fixed-size canvas element on the page. In many mobile apps we will want instead for the canvas element to extend over a some portion of the device’s screen. To guess at how to do this, you might try to set the width and height properties of the element to n% e.g. with something like:

canvas
load more v

Other "html5-display" queries related to "Image drawn to HTML5 Canvas does not display correctly on first load"