如何从系统中获取图像以在html5中加载到画布中 [英] How to fetch image from system to load in canvas in html5

查看:198
本文介绍了如何从系统中获取图像以在html5中加载到画布中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下方式: -

I am using the following way:-

代码

<!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>

我想在画布中加载此图片。在imageObj.src中传递图片网址是正确的方式吗?

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 ?

感谢提前

推荐答案

你几乎是对的。如果您在本地加载文件,则需要在路径前加上 file:///

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

我认为所有浏览器都会要求你拥有图像存储在与当前HTML页面相同的目录中或存储在当前HTML页面的子目录中,这样本地HTML页面就无法从硬盘驱动器中获取所有内容。

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建议您创建相对于当前HTML文档的路径。如果页面位于 file:/// C:/Users/shanky/webpages/page.html ,那么只需使用:

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";

加载位于的图像文件:/// C:/ Users /shanky/webpages/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.

请注意,大多数浏览器对 文件的相同来源政策:资源。在简单的本地服务器上托管您的应用程序并使用 http:// localhost 访问它可能更容易。

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.

这篇关于如何从系统中获取图像以在html5中加载到画布中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆