简体   繁体   English

如何从系统中获取图像以将其加载到HTML5中的画布中

[英]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 ? 在imageObj.src中传递图像URL是否正确?

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:/// : 如果要在本地加载文件,则需要在路径file:///加上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. 我认为所有浏览器都要求您将图像存储在当前HTML页面的同一目录中或子目录中,以便本地HTML页面无法从硬盘驱动器上抓取所有内容。

I'd suggest you make the path relative to your current HTML document. 我建议您创建相对于当前HTML文档的路径。 If the page is at file:///C:/Users/shanky/webpages/page.html then just use: 如果页面位于file:///C:/Users/shanky/webpages/page.html则只需使用:

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

to load an image located at file:///C:/Users/shanky/webpages/img/Demo.jpg . 加载位于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. 如果将页面移动到新文件夹或将其托管在不再使用file:协议的服务器上,则可以更轻松地进行操作。

Note that most browsers are pretty finicky about the same origin policy for file: resources . 请注意,大多数浏览器file: resources相同原始策略非常挑剔。 It may be easier to host your application on a simple local server and access it with http://localhost . 将应用程序托管在简单的本地服务器上并使用http://localhost访问可能更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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