Home > Article > Web Front-end > 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>
<code class="css">canvas#viewport { border: 1px solid white; width: 900px; }</code>
<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>
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!