简体   繁体   中英

How to fetch image from system to load in canvas in html5

I am using the following way:-

CODE

<!DOCTYPE HTML>
<html>
<head>
  <style>
   body {
     margin: 0px;
      padding: 0px;
   }
   #myCanvas {
     border: 1px solid #9C9898;
   }
  </style>
 <script>
  window.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    var imageObj = new Image();

    imageObj.onload = function() {
      context.drawImage(imageObj, 69, 50);
    };
    imageObj.src = "C:\Images\Demo.jpg";
  };

</script>
</head>
<body>
  <canvas id="myCanvas" width="578" height="400"></canvas>
</body>
</html>

i want to load this image in canvas. Is it right way to pass image URL in imageObj.src ?

or is there any other way to load the image ?

THANKS IN ADVANCE

You have it nearly right. If you are loading the file locally, you need to prefix your path with file:/// :

imageObj.src = "file:///C:/Images/Demo.jpg";  // also, use forward slashes, not backslashes

I think all browsers will require you to have the image stored in the same directory as or in a subdirectory from the current HTML page, so that local HTML pages can't go grabbing things from all over your hard drive.

I'd suggest you make the path relative to your current HTML document. If the page is at file:///C:/Users/shanky/webpages/page.html then just use:

imageObj.src = "img/Demo.jpg";

to load an image located at file:///C:/Users/shanky/webpages/img/Demo.jpg . This makes it easier if you move your page to a new folder or host it on a server, where it no longer uses the file: protocol.

Note that most browsers are pretty finicky about the same origin policy for file: resources . It may be easier to host your application on a simple local server and access it with http://localhost .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM