html5调用手机摄像头和相册,h5 调用手机摄像头/相册

html 部分

js 部分

getBase64: function (file, callback) {

var maxWidth = 640

if (file.files && file.files[0]) {

var thisFile = file.files[0]

// if (thisFile.size > 524288) {

//    this.showToast("图片不能超过512k!");

//  return;

// }

var reader = new FileReader()

reader.onload = function (event) {

var imgUrl = event.target.result

var img = new Image()

img.onload = function () {

var canvasId = 'canvasBase64Imgid',

canvas = document.getElementById(canvasId)

if (canvas != null) {

document.body.removeChild(canvas)

}

var canvas = document.createElement('canvas')

canvas.innerHTML = 'New Canvas'

canvas.setAttribute('id', canvasId)

canvas.style.display = 'none'

document.body.appendChild(canvas)

canvas.width = this.width

canvas.height = this.height

var imageWidth = this.width,

imageHeight = this.height

if (this.width > maxWidth) {

imageWidth = maxWidth

imageHeight = this.height * maxWidth / this.width

canvas.width = imageWidth

canvas.height = imageHeight

}

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

context.clearRect(0, 0, imageWidth, imageHeight)

context.drawImage(this, 0, 0, imageWidth, imageHeight)

var base64 = canvas.toDataURL('image/png', 1)

var imgbase = base64.substr(22)

callback(imgbase)

// this.imgUrl =

}

img.src = imgUrl

}

reader.readAsDataURL(file.files[0])

}

},

uploadChange: function (event) {

if (event.target.files.length > 0) {

this.files = event.target.files[0] // 提交的图片

this.getBase64(event.target, url => {

document.getElementById("appealimg1").src='data:image/png;base64,' + url

})

}

this.isShowUp = false

}

以上代码,只能上传单张照片,如果需要在同一界面上传多张照片,就要再写一个函数,用新的函数接收下标值,来判断当前点击的是哪一张,在调用uploadChange函数的函数,后面就可以拼接下标值了