HTML画布允许用户从文件加载图像

时间:2018-04-02 17:38:37

标签: javascript jquery p5.js

我正在尝试在画布上创建一个功能,用户单击一个加载按钮,允许他们从计算机上的任何文件加载图像,然后加载图像以填充画布。我已经把我到目前为止的内容包括在内了:

function loadTool() {
  var img;
  this.name = "loadTool";
  this.icon = "assets/loadButton.png";
  img = loadImage("assets/star.png");

  this.draw = function() {
    background(img, 0, 0);
  }
}

我正在使用p5.js库。我不想手动从loadImage加载图像,而是允许用户选择保存在计算机上的图像,并用图像填充画布。

2 个答案:

答案 0 :(得分:2)

您可以使用P5.dom助手库提供的createFileInput()功能。

来自the reference

var input; 
var img; 

function setup() { 
  input = createFileInput(handleFile); 
  input.position(0, 0); 
} 

function draw() { 
  if (img) { 
    image(img, 0, 0, width, height); 
  } 
} 

function handleFile(file) { 
  print(file); 
  if (file.type === 'image') { 
    img = createImg(file.data); 
    img.hide(); 
  } 
}

答案 1 :(得分:0)

这是一种非jQuery的方式 HTML:

<input type='file' />
<br><img id="myImg" src="#" alt="your image" height=200 width=100>

JS:

window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', 
    function() {
       if (this.files && this.files[0]) {
         var img = document.querySelector('img');  // $('img')[0]
         img.src = URL.createObjectURL(this.files[0]); // set src to file url (You in your case would run your p5.js code)
         img.onload = iLoad; // optional onload event listener
      }
  });
});

function iLoad(e) { /*This method is just mostly used for waiting for the image to load, you can redact it if it isn't needed.*/ }