html5 如何调用手机相册

html-css014

html5 如何调用手机相册,第1张

需要加载cordova.js

方法:

document.addEventListener("deviceready", onDeviceReady, false)

function onDeviceReady() {

pictureSource = navigator.camera.PictureSourceType

destinationType = navigator.camera.DestinationType

}

//相册

function fromCamera()

{

var source = pictureSource.PHOTOLIBRARY

navigator.camera.getPicture(function (imageData) {

setimg(imageData)

}, function (message) {

if (source == pictureSource.CAMERA)

alert('加载照相机出错!' + message)

else

alert('加载相册出错!' + message)

}, {

quality: 50,

destinationType: destinationType.FILE_URI,

sourceType: source

})

}

//拍照

function EditImgPz()

{

navigator.camera.getPicture(function (imageData) {

setimg(imageData)

}, function (message) {

alert(message)

}, {

quality: 50,

destinationType: navigator.camera.DestinationType.FILE_URI,

sourceType: Camera.PictureSourceType.CAMERA,

allowEdit: true,

encodingType: Camera.EncodingType.JPEG,

popoverOptions: CameraPopoverOptions,

saveToPhotoAlbum: true

})

}

先简单的添加需要的控件

<video id="video" autoplay=""style='width:640pxheight:480px'></video>

<button id='picture'>PICTURE</button>

<canvas id="canvas" width="640" height="480"></canvas>

并在script中定义

var video = document.getElementById("video")

var context = canvas.getContext("2d")

var errocb = function () {

console.log('sth wrong!')

}

然后,简单的说就是利用html5的api navigator.getUserMedia来开启设备的摄像头,浏览器上会出现图示中的提示

if (navigator.getUserMedia) { // 标准的API

navigator.getUserMedia({ "video": true }, function (stream) {

video.src = stream

video.play()

}, errocb)

} else if (navigator.webkitGetUserMedia) { // WebKit 核心的API

navigator.webkitGetUserMedia({ "video": true }, function (stream) {

video.src = window.webkitURL.createObjectURL(stream)

video.play()

}, errocb)

}

网上有些例子中,navigator.getUserMedia第一个参数是‘video’,这可能是早期的版本,现在必须是obj

还有关于getUserMedia和webkitGetUserMedia 的判断,网上有这么写的

navigator.getUserMedia = (navigator.getUserMedia ||

navigator.webkitGetUserMedia ||

navigator.mozGetUserMedia ||

navigator.msGetUserMedia)

但要注意,他们绑定video.src的方法不一样,偶没有测过createObjectURL是否通用

拍照功能就是简单的调用canvas中的drawImage即可

document.getElementById("picture").addEventListener("click", function () {

context.drawImage(video, 0, 0, 640, 480)

})

1、实现头的方法代码。

2、编写CSS样式的方法代码。

3、html上传代码。

4、JS处理方法代码。

5、测试结果如下。

注意事项:

JavaScript是一种网络脚本语言,在web应用开发中得到了广泛的应用,它经常被用来为网页添加各种动态功能,为用户提供更加流畅美观的浏览效果,通常JavaScript脚本被嵌入到HTML中来实现自己的功能。