鸿蒙next开发:Web组件中网页长截图的方案

介绍

本案例实现了Web组件中网页长截图的方案。支持截图后展示大小浮窗预览、保存图片到相册、手势左滑关闭等功能。

效果图预览

实现思路

本解决方案通过循环滚动Web组件,每次滚动截取当前状态后拼接到离屏画布,最后一次性转为PixelMap图片并显示在全屏模态窗口中。再通过安全控件SaveButton以免权限申请的方式保存到用户的相册中。

  • 创建Web组件加载指定的网页,获取Web组件和网页的实际尺寸,并给Web组件绑定自定义的id。

由于Web组件为自适应填充剩余空间,所以通过onAreaChange接口来获取Web组件的实际尺寸。 Web网页加载完成后在onPageEnd回调中通过WebviewController的接口runJavaScriptExt执行javascript代码以获取网页的实际大小。

Web({
  src: this.webPageUrl,
  controller: this.webviewController
})
  .id(Constants.WEB_ID)
  .onAreaChange((oldValue, newValue) => {
    this.webWidth = newValue.width as number;
    this.webHeight = newValue.height as number;
    logger.info(TAG, `Web component width: ${this.webWidth}, height: ${this.webHeight}`);
  })
  .onPageEnd(() => {
    const script = '[document.documentElement.scrollWidth, document.documentElement.scrollHeight]';
    this.webviewController.runJavaScriptExt(script).then((result) => {
      switch (result.getType()) {
        case webview.JsMessageType.ARRAY:
          this.h5Width = (result.getArray() as number[])[0]; // 这里的单位是vp
          this.h5Height = (result.getArray() as number[])[1];
          logger.info(TAG, `h5Width = ${this.h5Width}, h5Height = ${this.h5Height}`);
          break;
        default:
          logger.error(TAG, `Get web page size tyep error.`);
          break;
      }
    });
  })
  • 创建截图函数,执行滚动截图并拼接。

截图的次数为网页高度/Web组件高度向上取整的结果。 最后一次截图的图片需要特殊处理,去除重复的部分,重复的部分高度即网页高度/Web组件高度取余。通过PixelMap对象的接口crop进行裁剪。

const snipTimes = Math.ceil(this.h5Height / this.webHeight);
for (let i = 0; i < snipTimes; i++) {
  let curSnip = await componentSnapshot.get(Constants.WEB_ID);
  // 最后一次截图需要特殊处理,去除重复部分
  if (i === snipTimes - 1) {
    let h = this.h5Height % this.webHeight;
    // 裁剪
    await curSnip.crop({ x: 0, y: vp2px(this.webHeight - h),
      size: {
        height: vp2px(h),
        width: vp2px(this.webWidth)
      }
    });
    offCanvasCtx.drawImage(curSnip, 0, this.webHeight * i, this.webWidth, h);
 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值