这里要用到一个 h5 的属性capture
由于h5项目中使用到了文件上传的功能,这里来写一下 html5的一个属性 capture 的使用。
直接使用 type= "file" 加上 accept="image/*"就会默认调起系统的图片文件。
当你需要直接唤起相机的时候 capture="camera"
需要支持多选的时候 multiple="multiple"
复制代码下面是关于 capture 属性的详细阐述
概述
The HTML Media Capture specification extends the HTMLInputElement interface with a capture attribute. The capture attribute allows authors to declaratively request use of a media capture mechanism, such as a camera or microphone, from within a file upload control, for capturing media on the spot.
这个 html 的媒体属性允许开发者调用一些设备的媒体功能。
调用前置摄像头
To take a picture using the device's user-facing camera, and upload the picture taken using an HTML form:
复制代码
调用后置摄像头
Or alternatively, to capture video using the device's local video camera facing the environment:
复制代码
调用麦克风和摄像
Or alternatively, to capture audio using the device's local microphone (without preferred facing mode defined, falls back to the implementation-specific default facing mode):
复制代码
处理上传文件-XMLHttpRequest、
And handle the file upload in script via XMLHttpRequest:
var input = document.querySelector('input[type=file]'); // see Example 4
input.onchange = function (){
var file = input.files[0];
upload(file);
drawOnCanvas(file); // see Example 6
displayAsImage(file); // see Example 7
};
function upload(file){
var form = new FormData(),
xhr = new XMLHttpRequest();
form.append('image', file);
xhr.open('post', 'server.php', true);
xhr.send(form);
}
复制代码
使用 fileReader 和 canvas
The image can also be displayed on the client-side without uploading it e.g. for client-side image editing purposes, using the FileReader and a canvas element:
function drawOnCanvas(file){
var reader = new FileReader();
reader.onload = function (e){
var dataURL = e.target.result,
c = document.querySelector('canvas'), // see Example 4
ctx = c.getContext('2d'),
img = new Image();
img.onload = function(){
c.width = img.width;
c.height = img.height;
ctx.drawImage(img, 0, 0);
};
img.src = dataURL;
};
reader.readAsDataURL(file);
}
复制代码很多时间我们会处理上传的文件为 canvas
使用 createObjectURL()和图片处理
Or alternatively, to just display the image, using the createObjectURL() method and an img element:
function displayAsImage(file){
var imgURL = URL.createObjectURL(file),
img = document.createElement('img');
img.onload = function(){
URL.revokeObjectURL(imgURL);
};
img.src = imgURL;
document.body.appendChild(img);
}
复制代码
引用