鸿蒙next 带你玩转Web组件拉起相机进行拍照

前言导读

在鸿蒙next项目开发中,是不是经常会碰到跟h5交互 ,甚至还有直接在网友里面加载的图片 ,那么今天我们就分享给 各位一个案例 Web组件拉起相机进行拍照 然后显示在我们网页上面

效果图

具体实现

声明 WebviewController
ini 复制代码
controller: web_webview.WebviewController = new web_webview.WebviewController();
加载我们本地html
css 复制代码
Column() {
  Web({ src: $rawfile("camera.html"), controller: this.controller })

    .margin({ top: 40 })
    .backgroundColor(Color.Black)
}
.backgroundColor(Color.Black)
资源存放在我们 resources下面的rawfile目录下面

定义FileResult model

ini 复制代码
class FileResult {
  result: FileSelectorResult;
  fileSelector: FileSelectorParam;

  constructor(result: FileSelectorResult, fileSelector: FileSelectorParam) {
    this.result = result;
    this.fileSelector = fileSelector;
  }
}

实现 onShowFileSelector 方法

我们实现 onShowFileSelector方法并将我们的FileResult 对象传入

css 复制代码
Web({ src: $rawfile("camera.html"), controller: this.controller })
  .onShowFileSelector((event: FileResult) => {
    this.invokeCamera(((uri: string) => {
      event?.result.handleFileList([uri]);
    }))
    return true;
  })
  .margin({ top: 40 })
  .backgroundColor(Color.Black)
打开相机逻辑
typescript 复制代码
invokeCamera(callback: (uri: string) => void) {
  const context = this.getUIContext().getHostContext() as common.UIAbilityContext;
  const want: Want = {
    action: "ohos.want.action.imageCapture",
    parameters: {
      'callBundleName': context.abilityInfo.bundleName,
    }
  };
  const result: (error: BusinessError, data: common.AbilityResult) => void = (error: BusinessError,
    data: common.AbilityResult) => {
    const resultUri: string = data.want?.parameters?.resourceUri as string;
    if (callback && resultUri) {
      callback(resultUri);
    }
  }
  context.startAbilityForResult(want, result);
}

完整代码

typescript 复制代码
import web_webview from '@ohos.web.webview';
import { common, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';




class FileResult {
  result: FileSelectorResult;
  fileSelector: FileSelectorParam;

  constructor(result: FileSelectorResult, fileSelector: FileSelectorParam) {
    this.result = result;
    this.fileSelector = fileSelector;
  }
}

@Entry
@Component
struct Index {
  controller: web_webview.WebviewController = new web_webview.WebviewController();

  build() {
    Column() {
      Web({ src: $rawfile("camera.html"), controller: this.controller })
        .onShowFileSelector((event: FileResult) => {
          this.invokeCamera(((uri: string) => {
            event?.result.handleFileList([uri]);
          }))
          return true;
        })
        .margin({ top: 40 })
        .backgroundColor(Color.Black)
    }
    .backgroundColor(Color.Black)
  }


  invokeCamera(callback: (uri: string) => void) {
    const context = this.getUIContext().getHostContext() as common.UIAbilityContext;
    const want: Want = {
      action: "ohos.want.action.imageCapture",
      parameters: {
        'callBundleName': context.abilityInfo.bundleName,
      }
    };
    const result: (error: BusinessError, data: common.AbilityResult) => void = (error: BusinessError,
      data: common.AbilityResult) => {
      const resultUri: string = data.want?.parameters?.resourceUri as string;
      if (callback && resultUri) {
        callback(resultUri);
      }
    }
    context.startAbilityForResult(want, result);
  }
}

html代码

xml 复制代码
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8">
    <style>
        body {
          font-family: Arial, Helvetica, sans-serif, sans-serif;
          text-align: center;
          background-color: #000000;
          margin: 0;
        }
        #image {
          display: none;
          width: 100%;
          height: auto;
          padding-top: 50px;
        }
        #image_preview {
          display: none;
          margin-top: 15px;
        }
        .a-upload {
          text-decoration:none;
          padding: 10px 20px;
          height: 20px;
          line-height: 20px;
          position: relative;
          cursor: pointer;
          color: #ffffff;
          background-color: rgb(10, 89, 247);
          border-radius: 20px;
          overflow: hidden;
          display: inline-block;
          *display: inline;
          *zoom: 1
        }
        .a-upload  input {
            position: absolute;
            font-size: 100px;
            right: 0;
            top: 0;
            opacity: 0;
            filter: alpha(opacity=0);
            cursor: pointer
            border-radius: 20px;
            background: rgb(10, 89, 247);
        }
         .upload-button {
             padding: 6px 25px;
             background: #00bfff;
             border-radius: 4px;
             color: white;
             cursor: pointer;
             }
    </style>
</head>

<body>
<script>
    function showPic() {
      let event = this.event;
      let tFile = event ? event.target.files : [];
      if (tFile === 0) {
        document.getElementById('image_preview').style.display = 'block';
        document.getElementById('image_preview').innerHTML = "未选择图片";
        return;
      }
      document.getElementById('image').setAttribute('src', URL.createObjectURL(tFile[0]));
      document.getElementById('image_preview').style.display = 'block';
      document.getElementById('image').style.display = 'block';
    }
</script>

<a href="javascript:;" class="a-upload" id="a_upload">
    <label class="input-file-button" for="upload">相机</label>
    <input type="file" id="upload" name="upload" accept="image/*" capture="upload" onchange="showPic()"/>
</a>
<p id="image_preview"></p>
<img id="image">
</body>

</html>

网页效果

最后总结

Web组件拉起相机进行拍照然后显示再网页上面 我们主要还是通过原生的代码去打开相机拍照后然后拿到图片的uri 后再去回调通知给html然后显示再我们的网页上面。更多的实用场景,各位同学可以拷贝代码去进行改造,今天的文章就分享到这里。我们下一期再见。今天的文章就讲到这里有兴趣的 关注我B站教程 了解更多鸿蒙开发的知识 可以关注坚果派公众号和我的B站课程

课程地址

www.bilibili.com/cheese/play...

项目内容:

1 常用布局组件的学习
2 网络请求工具类封装
3 arkui 生命周期启动流程
4 日志工具类的封装
5 自定义组合组件的封装
6 路由导航跳转的使用
7 本地地数据的缓存 以及缓存工具类的封装
8 欢迎页面的实现
9 登录案例和自动登录效果实现
10 请求网络数据分页上拉加载 下拉刷新的实现
11 list数据懒加载实现
12 webview组件的使用

如果使用更多好用的鸿蒙next三方库

友情链接

harmony-utils 一款功能丰富且极易上手的HarmonyOS工具库,借助众多实用工具类,致力于助力开发者迅速构建鸿蒙应用,能够满足各种不同的开发需求。

harmony-dialog 一款极为简单易用的零侵入弹窗,仅需一行代码即可轻松实现,无论在何处都能够轻松弹出。

相关推荐
GY-935 小时前
HarmonyOS - UIObserver(无感监听)
harmonyos
哼唧唧_5 小时前
新闻类鸿蒙应用全链路运维指南:高并发场景下的稳定保障
harmonyos·新闻·harmony os5·鸿蒙运维
zacksleo7 小时前
哪些鸿蒙原生应用在使用Flutter
前端·flutter·harmonyos
二流小码农8 小时前
鸿蒙开发:简单实现一个服务卡片
harmonyos
移动端开发者9 小时前
鸿蒙Next数据面板组件DataPanel介绍
harmonyos
移动端开发者9 小时前
鸿蒙Next使用Canvas绘制一个汽车仪表盘
harmonyos
移动端开发者9 小时前
鸿蒙Next数据量环形图标Gauge介绍
harmonyos
塞尔维亚大汉9 小时前
鸿蒙开发面试真题:鸿蒙操作系统的微内核架构有哪些优势?
面试·harmonyos
我睡醒再说10 小时前
纯血Harmony NETX 5小游戏实践:2048(附源文件)
游戏·华为·harmonyos·arkts
程序员小刘11 小时前
基于uni-app for HarmonyOS5 的跨平台组件库开发指南,以及组件示例
华为·uni-app·harmonyos