介绍
本案例实现了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);

最低0.47元/天 解锁文章
3106

被折叠的 条评论
为什么被折叠?



