Tell me why with this code:
<html> <body> <canvas id = 'c01' style = "width: 800; border: 1px solid black;"></canvas> <script> var canvas = document.getElementById("c01"); var ctx = canvas.getContext("2d"); var image = new Image(); image.onload = function() { canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; ctx.beginPath(); ctx.drawImage(image, 0, 0); ctx.lineWidth = "6"; ctx.strokeStyle = "red"; ctx.rect(canvas.width / 4, canvas.height / 4, canvas.width / 2, canvas.height / 2); ctx.stroke(); }; image.src = "https://icdn.lenta.ru/images/2019/03/31/13/20190331135912200/pic_5bfd003894e22bb0d70b775286b96a4f.jpg"; </script> </body> </html>
the image is displayed and a rectangle is on top of it - ALL OK
And with this:
<script> var canvas = document.getElementById("c01"); var ctx = canvas.getContext("2d"); var image = new Image(); image.onload = function() { canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; }; image.src = "https://icdn.lenta.ru/images/2019/03/31/13/20190331135912200/pic_5bfd003894e22bb0d70b775286b96a4f.jpg"; ctx.beginPath(); ctx.drawImage(image, 0, 0); ctx.lineWidth = "6"; ctx.strokeStyle = "red"; ctx.rect(canvas.width / 4, canvas.height / 4, canvas.width / 2, canvas.height / 2); ctx.stroke(); </script>
the canvas is constructed in the right size (with the image), but the image itself is not drawn, and the rectangle flashes for a second and disappears
Is this due to the fact that the image does not have time to load (asynchronous image.src)?
and how to do everything correctly?
if there are several images, then onload will hardly have to