element-takesnapshot.uvue 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <template>
  2. <view id="snapshot-content">
  3. <page-head title="对本页面根view截图"></page-head>
  4. <view class="uni-padding-wrap">
  5. <text>this is text</text>
  6. </view>
  7. <button class="uni-btn btn-TakeSnapshot" type="primary" @tap="takeSnapshotClick">
  8. 点击截图并替换显示下方图片
  9. </button>
  10. <image style="margin-left:auto;margin-right:auto;margin-top:20px;width:90%;" :src="snapImage" :mode="mode"
  11. @longpress="saveToAlbum"></image>
  12. </view>
  13. </template>
  14. <script lang="uts">
  15. export default {
  16. data() {
  17. return {
  18. mode: "center",//aspectFit
  19. snapImage: "/static/uni.png"
  20. }
  21. },
  22. methods: {
  23. takeSnapshotClick() {
  24. const view = uni.getElementById('snapshot-content')!
  25. view.takeSnapshot({
  26. success: (res) => {
  27. console.log(res.tempFilePath)
  28. this.snapImage = res.tempFilePath
  29. this.mode = 'widthFix'
  30. uni.showToast({
  31. title: '截图成功,路径:' + res.tempFilePath,
  32. icon: "none"
  33. })
  34. },
  35. fail: (res) => {
  36. console.log(res)
  37. uni.showToast({
  38. icon: 'error',
  39. title: '截图失败'
  40. })
  41. }
  42. })
  43. },
  44. saveToAlbum(e : TouchEvent) {
  45. // console.log(e.currentTarget!.getAttribute("src"));
  46. let filePath : string = e.currentTarget!.getAttribute("src") as string
  47. uni.showActionSheet({
  48. itemList: ["保存"],
  49. success: res => {
  50. // console.log(res.tapIndex);
  51. if (res.tapIndex == 0) {
  52. uni.saveImageToPhotosAlbum({
  53. filePath: filePath,
  54. success() {
  55. uni.showToast({
  56. position: "center",
  57. icon: "none",
  58. title: "图片保存成功,请到手机相册查看"
  59. })
  60. },
  61. fail(e) {
  62. uni.showModal({
  63. content: "保存相册失败,errCode:" + e.errCode + ",errMsg:" + e.errMsg + ",errSubject:" + e.errSubject,
  64. showCancel: false
  65. });
  66. }
  67. })
  68. }
  69. },
  70. fail: () => { },
  71. complete: () => { }
  72. });
  73. }
  74. }
  75. }
  76. </script>