element-takesnapshot.uvue 2.3 KB
Newer Older
1
<template>
2
  <view id="snapshot-content">
A
Anne_LXM 已提交
3
    <page-head title="对本页面根view截图"></page-head>
4
    <view class="uni-padding-wrap">
A
Anne_LXM 已提交
5
      <text>this is text</text>
6
    </view>
7
    <button class="uni-btn btn-TakeSnapshot" type="primary" @tap="takeSnapshotClick">
8
      点击截图并替换显示下方图片
9
    </button>
DCloud-yyl's avatar
DCloud-yyl 已提交
10
    <image style="margin-left:auto;margin-right:auto;margin-top:20px;width:90%;" :src="snapImage" :mode="mode" @longpress="saveToAlbum"></image>
11 12 13 14
  </view>
</template>

<script lang="uts">
W
wanganxp 已提交
15 16 17
  export default {
    data() {
      return {
DCloud-yyl's avatar
DCloud-yyl 已提交
18
        mode: "center",//aspectFit
W
wanganxp 已提交
19 20 21 22 23 24 25
        snapImage: "/static/uni.png"
      }
    },
    methods: {
      takeSnapshotClick() {
        const view = uni.getElementById('snapshot-content')!
        view.takeSnapshot({
26
          success: (res) => {
W
wanganxp 已提交
27 28
            console.log(res.tempFilePath)
            this.snapImage = res.tempFilePath
DCloud-yyl's avatar
DCloud-yyl 已提交
29
            this.mode = 'widthFix'
W
wanganxp 已提交
30 31 32 33 34
            uni.showToast({
              title: '截图成功,路径:' + res.tempFilePath,
              icon: "none"
            })
          },
35
          fail: (res) => {
W
wanganxp 已提交
36 37 38 39 40 41
            console.log(res)
            uni.showToast({
              icon: 'error',
              title: '截图失败'
            })
          }
42
        })
W
wanganxp 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
      },
      saveToAlbum(e : TouchEvent) {
        // console.log(e.currentTarget!.getAttribute("src"));
        let filePath : string = e.currentTarget!.getAttribute("src") as string
        uni.showActionSheet({
          itemList: ["保存"],
          success: res => {
            // console.log(res.tapIndex);
            if (res.tapIndex == 0) {
              uni.saveImageToPhotosAlbum({
                filePath: filePath,
                success() {
                  uni.showToast({
                    position: "center",
                    icon: "none",
                    title: "图片保存成功,请到手机相册查看"
                  })
                },
                fail(e) {
                  uni.showModal({
                    content: "保存相册失败,errCode:" + e.errCode + ",errMsg:" + e.errMsg + ",errSubject:" + e.errSubject,
                    showCancel: false
                  });
                }
              })
            }
          },
          fail: () => { },
          complete: () => { }
        });
      }
74 75 76
    }
  }
</script>