本文实例为大家分享了vue实现调取手机摄像头和相册的具体代码,供大家参考,具体内容如下
自己总结的手机端拍照和相册原生的方法
HTML代码
<div> //要显示的图片 <div class="imgBox name"> <img :src="imgSrc" /> </div> <van-action-sheet v-model="show1"> <ul> <li class="paizhao" @click="captureImage()">拍照</li> <li class="paizhao" @click="galleryImg()">从相册选择</li> <li class="paizhao" @click="quxiao()">取消</li> </ul> </van-action-sheet> </div>
js逻辑代码
//data里声明的变量 data(){ return{ imgSrc: "", //展示的图片路径 tupianlist: "", //展示的图片容器 } }
在methods事件方法定义事件名
methods:{ // 从相册中选取图片 galleryImg() { let This = this; console.log("从相册中选择图片:"); plus.gallery.pick(function(path) { This.imgSrc = path; //path 是本地路径 let img = new Image(); img.src = path; img.onload = function(path) { var that = img; var w = that.width, //320 h = that.height, //426 scale = w / h; w = 320 || w; h = w / scale; var canvas = document.createElement("canvas"); canvas.width = 300; //这个设置不能丢,否者会成为canvas默认的300*150的大小 canvas.height = 300; //这个设置不能丢,否者会成为canvas默认的300*150的大小 var ctx = canvas.getContext("2d"); ctx.drawImage(that, 0, 0, 300, 300); var base64 = canvas.toDataURL( "image/png", "image/jpeg", "image/jpg", 1 || 0.8 ); This.tupianlist = base64; // console.log(This.tupianlist + "我是转码后的base"); //这里可以请求接口 }; }); }, // 拍照 captureImage() { let This = this; var cmr = plus.camera.getCamera(); //获取摄像头管理对象 var res = cmr.supportedImageResolutions[0]; //字符串数组,摄像头支持的拍照分辨率 var fmt = cmr.supportedImageFormats[0]; //字符串数组,摄像头支持的拍照文件格式 // console.log("拍照分辨率: " + res + ", 拍照文件格式: " + fmt); cmr.captureImage( function(path) { plus.gallery.save(path, params => { let file = params.file; //编码为base64 var img = new Image(); img.src = file; img.onload = function() { var that = img; var w = that.width, h = that.height, scale = w / h; w = 320 || w; h = w / scale; var canvas = document.createElement("canvas"); canvas.width = 300; //这个设置不能丢,否者会成为canvas默认的300*150的大小 canvas.height = 300; //这个设置不能丢,否者会成为canvas默认的300*150的大小 var ctx = canvas.getContext("2d"); ctx.drawImage(that, 0, 0, 300, 300); var base64 = canvas.toDataURL( "image/png", "image/jpeg", "image/jpg", 1 || 0.8 ); // console.log(base64); This.tupianlist = base64; //这里可以请求接口 }; }); //进行拍照操作 // 通过URL参数获取目录对象或文件对象 plus.io.resolveLocalFileSystemURL(path, function(entry) { var tmpPath = entry.toLocalURL(); //获取目录路径转换为本地路径URL地址 This.imgSrc = tmpPath; // alert("拍摄成功: " + tmpPath); }); }, function(error) { //捕获图像失败回调 // alert("捕获图像失败: " + error.message); }, { resolution: res, format: fmt } ); this.show1 = false; }, }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持NICE源码。