How to load a raster file in HTML5 Canvas

I am trying to load a bitmap into a canvas, following the example here.

Here is my code:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>HTML 5 Reports</title>
    <script type="text/javascript">
     function draw() {  
      var ctx = document.getElementById('canvas').getContext('2d');  
      var img = new Image();  
      img.onload = function(){  
       ctx.drawImage(img,0,0);  
       ctx.beginPath();  
       ctx.moveTo(30,96);  
       ctx.lineTo(70,66);  
       ctx.lineTo(103,76);  
       ctx.lineTo(170,15);  
       ctx.stroke();       }  
      img.src = 'worldmap1.bmp';  
    }  
    </script>
</head>
<body onload="draw()">
    <canvas id="graph"></canvas>
</body>
</html>

Nothing is displayed in the browser when viewing the page. No mistakes. Please tell me what I am doing wrong. Thank!

+3
source share
3 answers

I think I should answer this question to close it. Here is what meta.stackoverflow.com seems to be saying

Ok, I forgot the half column after draw (); and the canvas id should be "canvas" instead of "graph". Solved my own problem =) I feel smart now =) Thanks for helping everyone. - EddieC 2 minutes ago Edit.

+1
source

Canvas, , BMP... JPG, PNG GIF , .

+1

If its bitmap is not associated with other messages ... are you sure img.src is a valid file path?

0
source

Source: https://habr.com/ru/post/1758631/


All Articles