Javascript 我可以将本地文件加载到 html canvas 元素中吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13938686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:10:55  来源:igfitidea点击:

Can I load a local file into an html canvas element?

javascripthtml

提问by FunkyMonk91

My goal is to have users on iPad load an image into a canvas, then get the base 64 encoded said image all while being OFFLINE

我的目标是让 iPad 上的用户将图像加载到画布中,然后在离线时获取基本 64 编码的图像

JSFiddle

JSFiddle

JSFiddle

JSFiddle

Code

代码

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="../js/libs/jquery-1.7.1.min.js"></script>
    <script>
      $(document).ready(function(){ 
        //Get the canvas
        var canvas = document.getElementById('testCanvas');
        var context = canvas.getContext('2d');   

        $("#testButton").click(function(){
          var base_image = new Image();

          base_image.src = $("#testImg").val();
          //base_image.src = '1.jpg';

          //When the image loads
          $(base_image).load(function(){
            //Resize canvas for image
            $("#testCanvas").attr({
              width: base_image.width,
              height: base_image.height
            });

            //Draw image on canvas
            context.drawImage(base_image, 0, 0);

            //Get base64 encoded image
            var imageString = canvas.toDataURL("image/jpeg");
            $("#imageString").val(imageString);

            //alert($("#imageString").val().length);
            $("#imageOutput").attr("src", imageString);
          });//image load
        });//Test Button Click
      });//doc ready
    </script>
  </head>

  <body>
    <form>
      <input type="file" name="testImg" id="testImg" />
    </form>
    <button id="testButton">Test</button>
    <canvas id="testCanvas" style="border: 1px solid black;">Your Browser does not support canvas</canvas>
    <br />
    <fieldset>
      <legend>Image Data</legend>
      <textarea id="imageString"></textarea>

      <img id="imageOutput" src="" />
    </fieldset>
  </body>
</html>

I know the image isn't actually loaded from the <input type='file' />, but I figured it was worth a shot. In Chrome console I get:

我知道图像实际上不是从 加载的<input type='file' />,但我认为值得一试。在 Chrome 控制台中,我得到:

Not allowed to load local resource

不允许加载本地资源

Is there any way for me to get images from my iPad into a canvas element?

有什么方法可以让我将 iPad 中的图像放入画布元素中?

Any help, tips or advice is greatly appreciated! Thanks!

非常感谢任何帮助、提示或建议!谢谢!

回答by apsillers

I have a functioning fiddle(based on the prior work of this answer) that demonstrates how to upload an image using a file input, place it inside a canvas, and read the base64 data URL back out.

我有一个功能正常的小提琴(基于此答案的先前工作),它演示了如何使用文件输入上传图像,将其放置在画布中,然后读取 base64 数据 URL。

In short, you should:

简而言之,您应该:

  1. Use the File API to read in the image (you might do this in an onchangelistener of the input element):

    var file = input.files[0];
    var fr = new FileReader();
    fr.onload = createImage;   // onload fires after reading is complete
    fr.readAsDataURL(file);    // begin reading
    
  2. In your FileReader's onloadcallback (here, createImage), read the resultof the FileReader (here, fr.result). That's your image data URL!

  1. 使用文件 API 读取图像(您可以onchange在输入元素的侦听器中执行此操作):

    var file = input.files[0];
    var fr = new FileReader();
    fr.onload = createImage;   // onload fires after reading is complete
    fr.readAsDataURL(file);    // begin reading
    
  2. 在 FileReader 的onload回调(此处为createImage)中,读取resultFileReader 的fr.result。那是您的图像数据 URL!

OPTIONAL STEPS(only needed if you plan to manipulate the images on a canvas):

可选步骤(仅当您计划在画布上操作图像时才需要):

  1. In your FileReader's onloadcallback (here, createImage), make a new Imageobject and set its srcto the resultof the FileReader:

    img = new Image();
    img.onload = imageLoaded;
    img.src = fr.result;
    
  2. Finally, in your Image's onloadcallback, draw it to the canvas and then use canvas.toDataUrlto the data:

    canvas.width = img.width;      // set canvas size big enough for the image
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img,0,0);         // draw the image
    
    // do some manipulations...
    
    canvas.toDataURL("image/png");  // get the data URL
    
  1. 在您的FileReader的onload回调(这里createImage),使一个新的Image对象并将其设置srcresult了的FileReader的:

    img = new Image();
    img.onload = imageLoaded;
    img.src = fr.result;
    
  2. 最后,在 Image 的onload回调中,将其绘制到画布上,然后使用canvas.toDataUrl数据:

    canvas.width = img.width;      // set canvas size big enough for the image
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img,0,0);         // draw the image
    
    // do some manipulations...
    
    canvas.toDataURL("image/png");  // get the data URL