Estoy tratando de agregar un círculo sobre la imagen y también estoy usando la función .onload , pero el círculo aún se dibuja debajo de la imagen.
<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="1024" height="500" style="border:1px solid #d3d3d3;"> Your browser does not support the canvas element. </canvas> <script> var canvas = document.getElementById("myCanvas"); var background = new Image(); background.src = "https://i.imgur.com/ua7gL3M.png"; // Make sure the image is loaded first otherwise nothing will draw. background.onload = function(){ ctx.drawImage(background,0,0); } var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.arc(512,200,60,0,2*Math.PI); ctx.strokeStyle = "red" ctx.lineWidth = 5; ctx.stroke(); </script> </body> </html>Cuando ejecuto el fragmento de código, hay un breve momento en que el círculo es visible antes de que se represente la imagen. La imagen tiene que esperar para cargarse antes de renderizarse, pero el círculo se dibuja inmediatamente. Por eso, primero se dibuja el círculo y luego se coloca la imagen encima. Para solucionar esto, puede dibujar el círculo después de renderizar la imagen. Vea este fragmento de código revisado:
<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="1024" height="500" style="border:1px solid #d3d3d3;"> Your browser does not support the canvas element. </canvas> <script> var canvas = document.getElementById("myCanvas"); var background = new Image(); background.src = "https://i.imgur.com/ua7gL3M.png"; // Make sure the image is loaded first otherwise nothing will draw. background.onload = function(){ ctx.drawImage(background,0,0); // The following lines were moved into the onload callback ctx.beginPath(); ctx.arc(512,200,60,0,2*Math.PI); ctx.strokeStyle = "red" ctx.lineWidth = 5; ctx.stroke(); } var ctx = canvas.getContext("2d"); </script> </body> </html>