Browse Source

完善代码

ChenGanBin 2 years ago
parent
commit
aa1a59ff78
3 changed files with 123 additions and 65 deletions
  1. 2 1
      config/dev.ts
  2. 35 35
      src/core/components/watermark.vue
  3. 86 29
      src/pages/index/index.vue

+ 2 - 1
config/dev.ts

@@ -3,7 +3,8 @@ module.exports = {
     NODE_ENV: '"development"'
     NODE_ENV: '"development"'
   },
   },
   defineConstants: {
   defineConstants: {
-    "BASE_URL": '"http://localhost:8080"'
+    // "BASE_URL": '"http://localhost:8080"'
+    "BASE_URL": '"https://rss.zhixinghe1.top"'
   },
   },
   mini: {},
   mini: {},
   h5: {}
   h5: {}

+ 35 - 35
src/core/components/watermark.vue

@@ -1,14 +1,14 @@
 <template>
 <template>
   <view :class="classes" :style="{
   <view :class="classes" :style="{
     zIndex,
     zIndex,
-    backgroundSize: `${gapX + width}px`
+    backgroundSize: `${gapX + width}px`,
+    backgroundImage: `url('${base64Url}')`
   }">
   }">
   </view>
   </view>
 </template>
 </template>
 <script lang="ts">
 <script lang="ts">
 import { reactive, toRefs, computed, watch } from 'vue';
 import { reactive, toRefs, computed, watch } from 'vue';
 import Taro from '@tarojs/taro';
 import Taro from '@tarojs/taro';
-import { log } from 'console';
 export default {
 export default {
   props: {
   props: {
     name: {
     name: {
@@ -111,10 +111,10 @@ export default {
           ratio = res.pixelRatio;
           ratio = res.pixelRatio;
         }
         }
       });
       });
-      const canvasWidth = `${(gapX + width) * ratio}`;
-      const canvasHeight = `${(gapY + height) * ratio}`;
-      const markWidth = width * ratio;
-      const markHeight = height * ratio;
+      const canvasWidth = `${(gapX.value + width.value) * ratio}`;
+      const canvasHeight = `${(gapY.value + height.value) * ratio}`;
+      const markWidth = width.value * ratio;
+      const markHeight = height.value * ratio;
       const canvas: Taro.OffscreenCanvas = Taro.createOffscreenCanvas({
       const canvas: Taro.OffscreenCanvas = Taro.createOffscreenCanvas({
         type: '2d',
         type: '2d',
         width: Number(canvasWidth),
         width: Number(canvasWidth),
@@ -123,11 +123,11 @@ export default {
       const ctx: any = canvas.getContext('2d');
       const ctx: any = canvas.getContext('2d');
 
 
       if (ctx) {
       if (ctx) {
-        if (image) {
+        if (image.value) {
           // 创建一个图片
           // 创建一个图片
           const img = canvas.createImage() as HTMLImageElement;
           const img = canvas.createImage() as HTMLImageElement;
           dealWithImage(ctx, img, ratio, ctx.canvas, markWidth, markHeight);
           dealWithImage(ctx, img, ratio, ctx.canvas, markWidth, markHeight);
-        } else if (content) {
+        } else if (content.value) {
           dealWithText(ctx, ratio, ctx.canvas, markWidth, markHeight);
           dealWithText(ctx, ratio, ctx.canvas, markWidth, markHeight);
         }
         }
       } else {
       } else {
@@ -138,10 +138,10 @@ export default {
       const canvas = document.createElement('canvas');
       const canvas = document.createElement('canvas');
       const ratio = window.devicePixelRatio;
       const ratio = window.devicePixelRatio;
       const ctx = canvas.getContext('2d');
       const ctx = canvas.getContext('2d');
-      const canvasWidth = `${(gapX + width) * ratio}px`;
-      const canvasHeight = `${(gapY + height) * ratio}px`;
-      const markWidth = width * ratio;
-      const markHeight = height * ratio;
+      const canvasWidth = `${(gapX.value + width.value) * ratio}px`;
+      const canvasHeight = `${(gapY.value + height.value) * ratio}px`;
+      const markWidth = width.value * ratio;
+      const markHeight = height.value * ratio;
       canvas.setAttribute('width', canvasWidth);
       canvas.setAttribute('width', canvasWidth);
       canvas.setAttribute('height', canvasHeight);
       canvas.setAttribute('height', canvasHeight);
 
 
@@ -168,14 +168,14 @@ export default {
       ctx.rotate((Math.PI / 180) * Number(rotate));
       ctx.rotate((Math.PI / 180) * Number(rotate));
       img.crossOrigin = 'anonymous';
       img.crossOrigin = 'anonymous';
       img.referrerPolicy = 'no-referrer';
       img.referrerPolicy = 'no-referrer';
-      img.src = image; // 要加载的图片 url, 可以是base64
+      img.src = image.value; // 要加载的图片 url, 可以是base64
       img.onload = () => {
       img.onload = () => {
         ctx.drawImage(
         ctx.drawImage(
           img,
           img,
           (-imageWidth * ratio) / 2,
           (-imageWidth * ratio) / 2,
           (-imageHeight * ratio) / 2,
           (-imageHeight * ratio) / 2,
-          imageWidth * ratio,
-          imageHeight * ratio
+          imageWidth.value * ratio,
+          imageHeight.value * ratio
         );
         );
         ctx.restore();
         ctx.restore();
         state.base64Url = canvas.toDataURL();
         state.base64Url = canvas.toDataURL();
@@ -192,11 +192,11 @@ export default {
       ctx.textAlign = 'center';
       ctx.textAlign = 'center';
       // 文字绕中间旋转
       // 文字绕中间旋转
       ctx.translate(markWidth / 2, markHeight / 2);
       ctx.translate(markWidth / 2, markHeight / 2);
-      ctx.rotate((Math.PI / 180) * Number(rotate));
-      const markSize = Number(fontSize) * ratio;
-      ctx.font = `${fontStyle} normal ${fontWeight} ${markSize}px/${markHeight}px ${fontFamily}`;
-      ctx.fillStyle = fontColor;
-      ctx.fillText(content, 0, 0);
+      ctx.rotate((Math.PI / 180) * Number(rotate.value));
+      const markSize = Number(fontSize.value) * ratio;
+      ctx.font = `${fontStyle.value} normal ${fontWeight.value} ${markSize}px/${markHeight}px ${fontFamily.value}`;
+      ctx.fillStyle = fontColor.value;
+      ctx.fillText(content.value, 0, 0);
       ctx.restore();
       ctx.restore();
       state.base64Url = canvas.toDataURL();
       state.base64Url = canvas.toDataURL();
     };
     };
@@ -208,21 +208,21 @@ export default {
 
 
     watch(
     watch(
       () => [
       () => [
-        zIndex,
-        gapX,
-        gapY,
-        width,
-        height,
-        rotate,
-        image,
-        imageWidth,
-        imageHeight,
-        content,
-        fontStyle,
-        fontWeight,
-        fontColor,
-        fontSize,
-        fontFamily
+        zIndex.value,
+        gapX.value,
+        gapY.value,
+        width.value,
+        height.value,
+        rotate.value,
+        image.value,
+        imageWidth.value,
+        imageHeight.value,
+        content.value,
+        fontStyle.value,
+        fontWeight.value,
+        fontColor.value,
+        fontSize.value,
+        fontFamily.value
       ],
       ],
       () => {
       () => {
         init();
         init();

+ 86 - 29
src/pages/index/index.vue

@@ -1,21 +1,24 @@
 <template>
 <template>
   <view class="wrap">
   <view class="wrap">
-    <nut-cell>
-      <view v-if="state.editMode">
-        <img :src="state.imgSrc" alt="" />
-        <watermark v-if="state.editMode" :fullPage="false" font-color="#fa2c19" :content="state.watermarkContent">
-        </watermark>
-      </view>
-      <nut-empty v-if="!state.editMode" image="empty" description="无内容"></nut-empty>
-    </nut-cell>
-    <nut-cell v-if="!state.editMode">
-      <nut-button type='warning' size="large" shape="square" @click="chooseImg">选择图片</nut-button>
+    <nut-cell v-if="editMode">
+      <img :src="imgSrc" />
+      <watermark :fullPage="false" font-color="#fa2c19" :content="watermarkContent">
+      </watermark>
     </nut-cell>
     </nut-cell>
-    <view v-if="state.editMode">
-      <nut-input v-model="state.watermarkContent" placeholder="请输入要显示的水印内容" clearable clearSize="14" show-word-limit
-        :max-length="20" :showClearIcon="true" @update:model-value="refresh"></nut-input>
+    <view v-if="!editMode">
+      <view class="wrap-empty">
+        <nut-empty image="empty" description="无内容"></nut-empty>
+      </view>
+      <nut-cell>
+        <nut-button type='warning' size="large" shape="square" @click="chooseImg">选择图片</nut-button>
+      </nut-cell>
+    </view>
+    <view v-if="editMode">
+      <nut-input v-model="watermarkContent" placeholder="请输入要显示的水印内容" clearable clearSize="14" show-word-limit
+        :max-length="20" :showClearIcon="true"></nut-input>
       <nut-cell>
       <nut-cell>
-        <nut-button type='success' size="large" shape="square">下载</nut-button>
+        <nut-button type='success' size="large" shape="square" @click="downloadWatermarkImage"
+          :loading="downloadLoading">下载</nut-button>
       </nut-cell>
       </nut-cell>
     </view>
     </view>
   </view>
   </view>
@@ -25,6 +28,10 @@
 import { reactive, toRefs } from 'vue';
 import { reactive, toRefs } from 'vue';
 import { Plus } from '@nutui/icons-vue-taro';
 import { Plus } from '@nutui/icons-vue-taro';
 import watermark from '../../core/components/watermark.vue';
 import watermark from '../../core/components/watermark.vue';
+import { watch } from 'vue';
+import Taro from '@tarojs/taro';
+import httpClient from 'src/core/http';
+import { stat } from 'fs';
 export default {
 export default {
   name: 'Index',
   name: 'Index',
   components: {
   components: {
@@ -32,26 +39,79 @@ export default {
   },
   },
   setup() {
   setup() {
     const state = reactive({
     const state = reactive({
-      editMode: true,
-      imgSrc: "https://img10.360buyimg.com/ling/jfs/t1/181258/24/10385/53029/60d04978Ef21f2d42/92baeb21f907cd24.jpg",
+      imgSrc: "",
+      editMode: false,
       watermarkContent: '仅供入职使用',
       watermarkContent: '仅供入职使用',
+      downloadLoading: false
     });
     });
 
 
+    watch(() => state.imgSrc, (newVal, oldVal) => {
+      if (state.imgSrc) {
+        state.editMode = true;
+        return;
+      }
+      state.editMode = false;
+    })
+
     const chooseImg = function () {
     const chooseImg = function () {
-      state.editMode = !state.editMode;
-      console.log(state.editMode);
+      Taro.chooseImage({
+        success(res) {
+          let tempFilePaths = res.tempFilePaths;
+          if (tempFilePaths && tempFilePaths.length > 0) {
+            state.imgSrc = tempFilePaths[0];
+          }
+        }
+      })
     };
     };
 
 
-    const refresh = function () {
-      var tmpImgSrc = state.imgSrc;
-      state.imgSrc = '';
-      state.imgSrc = tmpImgSrc;
-    }
+    const downloadWatermarkImage = function () {
+      state.downloadLoading = true;
+      Taro.uploadFile({
+        url: BASE_URL + '/oss/upload', //仅为示例,非真实的接口地址
+        header: {
+          "Authorization": Taro.getStorageSync("token")
+        },
+        filePath: state.imgSrc,
+        name: 'files',
+        formData: {
+          'user': 'test'
+        },
+        success(ret) {
+          var retObj = JSON.parse(ret.data);
+          if (retObj.success && retObj.data.length > 0) {
+            Taro.setStorageSync("attachmentId", retObj.data[0]);
+            download();
+          }
+        },
+        complete() {
+          state.downloadLoading = false;
+        }
+      })
+    };
+
+    const download = () => {
+      Taro.downloadFile({
+        url: BASE_URL + '/oss/download?attachmentId=' + Taro.getStorageSync("attachmentId"), //仅为示例,并非真实的资源
+        header: {
+          "Authorization": Taro.getStorageSync("token")
+        },
+        success: function (res) {
+          // 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
+          if (res.statusCode === 200) {
+            console.log("下载成功了", res);
+            // TODO 这里要放到指定位置
+            Taro.saveImageToPhotosAlbum({
+              filePath: res.tempFilePath
+            });
+          }
+        }
+      })
+    };
 
 
     return {
     return {
-      state,
+      ...toRefs(state),
       chooseImg,
       chooseImg,
-      refresh
+      downloadWatermarkImage
     };
     };
   }
   }
 }
 }
@@ -63,11 +123,8 @@ export default {
   height: 100vh;
   height: 100vh;
   background-color: #eff2f5;
   background-color: #eff2f5;
 
 
-  .watermark {
+  &-empty {
     width: 100%;
     width: 100%;
-    height: 50vh;
-    margin-bottom: 20px;
-    display: block;
     background-color: #fff;
     background-color: #fff;
   }
   }
 }
 }