Home > Web Front-end > JS Tutorial > Why is my image not appearing on the HTML5 canvas, even though my code seems correct?

Why is my image not appearing on the HTML5 canvas, even though my code seems correct?

DDD
Release: 2024-10-30 11:02:02
Original
380 people have browsed it

Why is my image not appearing on the HTML5 canvas, even though my code seems correct?

Draw Image on HTML5 Canvas

You're attempting to add an image to a canvas, but it remains elusive. Let's uncover the secret behind this elusive endeavor.

Your code appears sound, so the issue must lie elsewhere. The critical step you're missing is ensuring the image is loaded before attempting to draw it.

Here's a revised solution:

<code class="html"><canvas id="viewport"></canvas></code>
Copy after login
<code class="css">canvas#viewport { border: 1px solid white; width: 900px; }</code>
Copy after login
<code class="javascript">var canvas = document.getElementById('viewport'),
    context = canvas.getContext('2d');

function make_base() {
  var base_image = new Image();
  base_image.src = 'img/base.png';
  base_image.onload = function() {
    context.drawImage(base_image, 0, 0);
  };
}

make_base();</code>
Copy after login

By adding an onload event listener to the image, you delay the drawing until the image is fully loaded, guaranteeing its presence on the canvas.

The above is the detailed content of Why is my image not appearing on the HTML5 canvas, even though my code seems correct?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template