瀏覽代碼

每日一签

xiaohaizhao 1 年之前
父節點
當前提交
0ac19a2c3b

+ 377 - 8
packageA/dailyYttendance/makePoster.vue

@@ -1,25 +1,394 @@
 <template>
     <view>
-        <!-- <lime-painter /> -->
+        <view class="head">
+            <view class="left">海报预览
+                <text class="text">
+                    (请拖动到下方编辑、保存海报)
+                </text>
+            </view>
+            <my-upload @uploadCallback="handleFileLink">
+                <view class="right">
+                    更换背景图
+                </view>
+            </my-upload>
+        </view>
+        <view class="painter-box">
+            <view>
+                <l-painter ref="painter" css="position: relative;">
+                    <!-- 背景图片 -->
+                    <l-painter-image :src="file.url" css="width: 280px; height: 500px" object-fit="fill" />
+                    <!-- 模板1 底部背景图 -->
+                    <l-painter-image v-if="mode == 'model1'"
+                        src="https://yossys06593.obs.cn-east-3.myhuaweicloud.com:443/202404101712714733820B3d50bdd4.png"
+                        css="width: 280px; height: 130px;position: absolute;bottom: 0;z-index: 1;" object-fit="fill" />
+                    <block v-if="mode == 'model1' || mode == 'model2'">
+                        <!-- 站点logo -->
+                        <l-painter-image :src="siteLogo"
+                            css="width: 60px; height:60px;position: absolute;bottom: 0px;left:10px;z-index: 2;"
+                            object-fit="cover" />
+                        <!-- 文字描述 -->
+                        <l-painter-text :text="painterText"
+                            :css="'width: 190px; line-height:20px;position: absolute;bottom: 62px;left:10px;z-index: 2;font-size: 14px;color: #333333;line-clamp:2;' + 'color:' + textColor" />
+                    </block>
+                    <!-- 二维码 -->
+                    <l-painter-qrcode v-if="mode != 'default' && detail.isqrcode" :text="detail.qrcodecontent"
+                        css="width: 64px; height: 64px;position: absolute;bottom: 22px;right:10px;z-index: 2;" />
+                </l-painter>
+            </view>
+        </view>
+
+        <view class="custom">
+            <view class="models">
+                <view class="group">
+                    <view class="title">海报样式</view>
+                    <view class="options">
+                        <view class="option" v-for="option in ops.painter" hover-class="navigator-hover" :key="option.mode"
+                            @click="mode = option.mode">
+                            <image v-if="option.imgUrl" class="image" :src="option.imgUrl" />
+                            <image class="current" v-if="option.mode == mode"
+                                src="https://yossys06593.obs.cn-east-3.myhuaweicloud.com:443/202404101712715614059B373541f3.png" />
+                        </view>
+                    </view>
+                </view>
+                <view class="group">
+                    <view class="title">文字色彩</view>
+                    <view class="options">
+                        <view class="option" v-for="option in ops.text" hover-class="navigator-hover" :key="option.name"
+                            @click="textColor = option.color">
+                            <view class="text" :style="option.style">
+                                {{ option.name }}
+                            </view>
+                            <image class="current" v-if="option.color == textColor"
+                                src="https://yossys06593.obs.cn-east-3.myhuaweicloud.com:443/202404101712715614059B373541f3.png" />
+                        </view>
+                    </view>
+                </view>
+            </view>
+
+            <view class="text-box">
+                <view class="title">
+                    海报文案
+                </view>
+                <view class="input-box">
+                    <input class="input" maxlength="16" type="text" v-model="painterText">
+                    <icon v-if="painterText" class="icon" type="clear" size="3.733vw" @click="painterText = ''" />
+                </view>
+            </view>
+            <view class="but" @click="loading ? '' : saveTheImage()" hover-class="navigator-hover">
+                <u-loading-icon v-if="loading" color="#fff" />
+                <text v-else>
+                    保存
+                </text>
+            </view>
+        </view>
+
+        <view class="tips">
+            *自定义海报区域可以选择海报样式、文字色彩等,文案部分最多可输入16个字,若留空,则不显示自定义文案。
+        </view>
+        <view style="height: 20px;" />
     </view>
 </template>
 
 <script>
-
+import myUpload from "../../components/my-upload.vue";
+import lPainter from "../../uni_modules/lime-painter/components/l-painter/l-painter.vue"
+import lPainterView from "../../uni_modules/lime-painter/components/l-painter-view/l-painter-view.vue"
+import lPainterText from "../../uni_modules/lime-painter/components/l-painter-text/l-painter-text.vue"
+import lPainterImage from "../../uni_modules/lime-painter/components/l-painter-image/l-painter-image.vue"
+import lPainterQrcode from "../../uni_modules/lime-painter/components/l-painter-qrcode/l-painter-qrcode.vue"
 export default {
-    components: {},
+    components: { lPainter, lPainterView, lPainterText, lPainterImage, lPainterQrcode, myUpload },
     data() {
         return {
             detail: {},
             file: {},
+            siteLogo: uni.getStorageSync('site').attinfos[0].url || '',
+            painterText: '自定义海报区域可以选择海报样式',
+            mode: "model1",
+            textColor: '#000000',
+            ops: {
+                painter: [{
+                    mode: "model1",
+                    imgUrl: "https://yossys06593.obs.cn-east-3.myhuaweicloud.com:443/202404101712714638752Bc18af43.png"
+                }, {
+                    mode: "model2",
+                    imgUrl: "https://yossys06593.obs.cn-east-3.myhuaweicloud.com:443/202404101712714646946B480ca84d.png"
+                }, {
+                    mode: "model3",
+                    imgUrl: "https://yossys06593.obs.cn-east-3.myhuaweicloud.com:443/202404101712714656283B28c9d1df.png"
+                }, {
+                    mode: "default"
+                }],
+                text: [{
+                    name: "灰色",
+                    color: '#999999',
+                    style: "color: #999999; background: #FFFFFF;border: 1px solid #DDDDDD;"
+                }, {
+                    name: "黑色",
+                    color: '#000000',
+                    style: 'color: #000000; background: #FFFFFF; border: 1px solid #DDDDDD;'
+                }, {
+                    name: "白色",
+                    color: '#FFFFFF',
+                    style: "color: #FFFFFF;background: #CCCCCC;"
+                },]
+            },
+            loading: false
         }
     },
     onLoad() {
-        this.detail = this.$Http.data.detail;
-        this.file = this.$Http.data.file;
-        delete (this.$Http.data)
-    }
+        try {
+            this.detail = this.$Http.data.detail;
+            this.file = this.$Http.data.file;
+            delete (this.$Http.data)
+        } catch (error) {
+
+        }
+    },
+    beforeDestroy() {
+        if (this.file.ownertable == "temporary") this.deteleFiles([this.file.linksid])
+    },
+    methods: {
+        saveTheImage() {
+            let that = this;
+            this.loading = true;
+            this.$refs.painter.canvasToTempFilePathSync({
+                fileType: "jpg",
+                // 如果返回的是base64是无法使用 saveImageToPhotosAlbum,需要设置 pathType为url
+                pathType: 'url',
+                quality: 1,
+                success: (res) => {
+                    // 非H5 保存到相册
+                    // H5 提示用户长按图另存
+                    uni.saveImageToPhotosAlbum({
+                        filePath: res.tempFilePath,
+                        success: function (e) {
+                            uni.showModal({
+                                title: '提示',
+                                content: '图片已保存到系统相册',
+                                showCancel: false
+                            })
+                            that.loading = false;
+                            this.$Http.basic({
+                                "id": 20240319142702,
+                                "content": {
+                                    sat_sharematerialid: that.detail.sat_sharematerialid, type: 1
+                                }
+                            }).then(res => {
+                                console.log(type, '记录', res)
+                            })
+
+                        },
+                        fail: ({ errMsg }) => {
+                            if (errMsg == 'saveImageToPhotosAlbum:fail auth deny') {
+                                uni.showModal({
+                                    title: '提示',
+                                    content: '请授权添加到相册权限后再试!',
+                                    showCancel: false,
+                                    complete: (complete) => {
+                                        uni.openSetting({
+                                            success: res => {
+                                                that.loading = false;
+                                                if (res.authSetting['scope.writePhotosAlbum']) {
+                                                    this.saveTheImage()
+                                                } else {
+                                                    uni.showModal({
+                                                        title: '提示',
+                                                        content: '未获取授权!已取消保存',
+                                                        showCancel: false,
+                                                    })
+                                                }
+                                            }
+                                        })
+                                    },
+                                })
+                            } else {
+                                that.loading = false;
+                                uni.showModal({
+                                    title: '提示',
+                                    content: '已取消保存',
+                                    showCancel: false,
+                                })
+                            }
+                        },
+                    });
+                },
+            });
+        },
+        handleFileLink(attachmentids, ownertable = "temporary", ownerid = 1, data) {
+            this.$Http.basic({
+                "classname": "system.attachment.Attachment",
+                "method": "createFileLink",
+                "content": {
+                    ownertable,
+                    ownerid,
+                    usetype: 'painter',
+                    attachmentids
+                }
+            }).then(res => {
+                console.log('绑定附件', res)
+                if (this.cutoff(res.msg)) return;
+                this.file = res.data[0];
+            })
+        },
+        //删除附件
+        deteleFiles(linksids) {
+            this.$Http.basic({
+                "classname": "system.attachment.Attachment",
+                "method": "deleteFileLink",
+                "content": {
+                    linksids
+                }
+            }).then(res => {
+                console.log("处理删除附件", res)
+                if (this.cutoff(res.msg)) return;
+            });
+        },
+    },
 }
 </script>
 
-<style></style>
+<style lang="scss">
+.head {
+    display: flex;
+    align-items: center;
+    justify-content: space-between;
+    padding: 10px;
+
+    .left {
+        line-height: 20px;
+        font-family: Source Han Sans SC, Source Han Sans SC;
+        font-size: 14px;
+        color: #333333;
+
+        .text {
+            color: #666666;
+        }
+    }
+
+}
+
+.custom {
+    width: 355px;
+    background: #FFFFFF;
+    border-radius: 8px;
+    padding: 10px;
+    box-sizing: border-box;
+    margin: 10px auto;
+
+    .models {
+        display: flex;
+        justify-content: space-between;
+
+        .group {
+            .title {
+                line-height: 20px;
+                font-family: Source Han Sans SC, Source Han Sans SC;
+                font-size: 14px;
+                color: #333333;
+                margin-bottom: 10px;
+            }
+
+            .options {
+                display: flex;
+
+                .option {
+                    position: relative;
+                    width: 40px;
+                    height: 40px;
+                    background: #CCCCCC;
+                    border-radius: 5px;
+                    margin-right: 5px;
+                    overflow: hidden;
+                    box-sizing: border-box;
+
+                    .image,
+                    .text {
+                        display: flex;
+                        align-items: center;
+                        justify-content: center;
+                        width: 100%;
+                        height: 100%;
+                        font-family: Source Han Sans SC, Source Han Sans SC;
+                        font-size: 12px;
+                        box-sizing: border-box;
+                        border-radius: 5px;
+                    }
+
+                    .current {
+                        position: absolute;
+                        height: 14px;
+                        width: 14px;
+                        top: 0;
+                        right: 0;
+                    }
+
+                }
+
+                .option:last-child {
+                    margin-right: 0;
+                }
+            }
+
+        }
+    }
+
+    .text-box {
+        margin-top: 20px;
+
+        .title {
+            line-height: 20px;
+            font-family: Source Han Sans SC, Source Han Sans SC;
+            font-size: 14px;
+            color: #333333;
+        }
+
+        .input-box {
+            display: flex;
+            align-items: center;
+            width: 335px;
+            height: 50px;
+            background: #FFFFFF;
+            border-radius: 8px;
+            border: 1px solid #CCCCCC;
+            margin-top: 10px;
+            padding: 10px;
+            box-sizing: border-box;
+
+            .input {
+                flex: 1;
+            }
+        }
+    }
+
+    .but {
+        display: flex;
+        align-items: center;
+        justify-content: center;
+        width: 333px;
+        height: 45px;
+        background: #C30D23;
+        border-radius: 5px;
+        margin-top: 20px;
+
+        font-family: PingFang SC, PingFang SC;
+        font-weight: bold;
+        font-size: 16px;
+        color: #FFFFFF;
+    }
+}
+
+.tips {
+    width: 355px;
+    height: 34px;
+    font-family: Source Han Sans SC, Source Han Sans SC;
+    font-size: 12px;
+    color: #666666;
+    margin: 10px auto;
+}
+
+.painter-box {
+    display: flex;
+    justify-content: center;
+}
+</style>

+ 22 - 2
pages/login/modules/dispose.js

@@ -13,6 +13,7 @@ function loginMsg(account_list, _this, storage = true) {
         query_userauth();
         // query_adspacelist();
         querySite_Parameter();
+        querySite()
     } else {
         uni.navigateTo({
             url: '/pages/login/selectSite'
@@ -45,7 +46,7 @@ function querySite_Parameter() {
         "method": "querySite_Parameter", //查询站点数据
         "content": {}
     }).then(res => {
-        console.log("查询站点数据", res)
+        console.log("查询站点配置", res)
         if (res.msg != '成功') return uni.showToast({
             title: res.msg,
             icon: "none"
@@ -55,6 +56,25 @@ function querySite_Parameter() {
         toHome();
     })
 }
+
+/* 查询站点数据 */
+function querySite() {
+    that.$Http.basic({
+        "classname": "webmanage.site.site",
+        "method": "querySite",
+        "content": {},
+    }).then(res => {
+        console.log("查询站点数据", res)
+        if (res.msg != '成功') return uni.showToast({
+            title: res.msg,
+            icon: "none"
+        });
+        uni.setStorageSync('site', res.data);
+        count += 1;
+        toHome();
+    })
+}
+
 /* 查询轮播图 */
 function query_adspacelist() {
     that.$Http.basic({
@@ -73,7 +93,7 @@ function query_adspacelist() {
 }
 
 function toHome() {
-    if (count < 2) return;
+    if (count < 3) return;
     uni.reLaunch({
         url: '/pages/index/index',
     });

+ 397 - 398
uni_modules/lime-painter/components/l-painter/l-painter.vue

@@ -8,8 +8,7 @@
 
 			<!-- #endif -->
 			<!-- #ifdef APP-NVUE -->
-			<web-view :style="size" ref="webview"
-				src="/uni_modules/lime-painter/hybrid/html/index.html"
+			<web-view :style="size" ref="webview" src="/uni_modules/lime-painter/hybrid/html/index.html"
 				class="lime-painter__canvas" @pagefinish="onPageFinish" @error="onError" @onPostMessage="onMessage">
 			</web-view>
 			<!-- #endif -->
@@ -19,443 +18,443 @@
 </template>
 
 <script>
-	import { parent } from '../common/relation'
-	import props from './props'
-	import {toPx, base64ToPath, pathToBase64, isBase64, sleep, getImageInfo }from './utils';
-	//  #ifndef APP-NVUE
-	import { canIUseCanvas2d, isPC} from './utils';
-	import Painter from './painter';
-	// import Painter from '@painter'
-	const nvue = {}
-	//  #endif
-	//  #ifdef APP-NVUE
-	import nvue from './nvue'
-	//  #endif
-	export default {
-		name: 'lime-painter',
-		mixins: [props, parent('painter'), nvue],
-		data() {
-			return {
-				use2dCanvas: false,
-				canvasHeight: 150,
-				canvasWidth: null,
-				parentWidth: 0,
-				inited: false,
-				progress: 0,
-				firstRender: 0,
-				done: false,
-				tasks: []
-			};
+import { parent } from '../common/relation'
+import props from './props'
+import { toPx, base64ToPath, pathToBase64, isBase64, sleep, getImageInfo } from './utils';
+//  #ifndef APP-NVUE
+import { canIUseCanvas2d, isPC } from './utils';
+import Painter from './painter';
+// import Painter from '@painter'
+const nvue = {}
+//  #endif
+//  #ifdef APP-NVUE
+import nvue from './nvue'
+//  #endif
+export default {
+	name: 'lime-painter',
+	mixins: [props, parent('painter'), nvue],
+	data() {
+		return {
+			use2dCanvas: false,
+			canvasHeight: 150,
+			canvasWidth: null,
+			parentWidth: 0,
+			inited: false,
+			progress: 0,
+			firstRender: 0,
+			done: false,
+			tasks: []
+		};
+	},
+	computed: {
+		styles() {
+			return `${this.size}${this.customStyle || ''};` + (this.hidden && 'position: fixed; left: 1500rpx;')
 		},
-		computed: {
-			styles() {
-				return `${this.size}${this.customStyle||''};` + (this.hidden && 'position: fixed; left: 1500rpx;')
-			},
-			canvasId() {
-				return `l-painter${this._ && this._.uid || this._uid}`
-			},
-			size() {
-				if (this.boardWidth && this.boardHeight) {
-					return `width:${this.boardWidth}px; height: ${this.boardHeight}px;`;
-				}
-			},
-			dpr() {
-				return this.pixelRatio || uni.getSystemInfoSync().pixelRatio;
-			},
-			boardWidth() {
-				const {width = 0} = (this.elements && this.elements.css) || this.elements || this
-				const w = toPx(width||this.width)
-				return w || Math.max(w, toPx(this.canvasWidth));
-			},
-			boardHeight() {
-				const {height = 0} = (this.elements && this.elements.css) || this.elements || this
-				const h = toPx(height||this.height)
-				return h || Math.max(h, toPx(this.canvasHeight));
-			},
-			hasBoard() {
-				return this.board && Object.keys(this.board).length
-			},
-			elements() {
-				return this.hasBoard ? this.board : JSON.parse(JSON.stringify(this.el))
+		canvasId() {
+			return `l-painter${this._ && this._.uid || this._uid}`
+		},
+		size() {
+			if (this.boardWidth && this.boardHeight) {
+				return `width:${this.boardWidth}px; height: ${this.boardHeight}px;`;
 			}
 		},
-		created() {
-			this.use2dCanvas = this.type === '2d' && canIUseCanvas2d() && !isPC
+		dpr() {
+			return this.pixelRatio || uni.getSystemInfoSync().pixelRatio;
 		},
-		async mounted() {
-			await sleep(30)
-			await this.getParentWeith()
-			this.$nextTick(() => {
-				setTimeout(() => {
-					this.$watch('elements', this.watchRender, {
-						deep: true,
-						immediate: true
-					});
-				}, 30)
-			})
+		boardWidth() {
+			const { width = 0 } = (this.elements && this.elements.css) || this.elements || this
+			const w = toPx(width || this.width)
+			return w || Math.max(w, toPx(this.canvasWidth));
 		},
-		// #ifdef VUE3
-		unmounted() {
-			this.done = false
-			this.inited = false
-			this.firstRender = 0
-			this.progress = 0
-			this.painter = null
-			clearTimeout(this.rendertimer)
+		boardHeight() {
+			const { height = 0 } = (this.elements && this.elements.css) || this.elements || this
+			const h = toPx(height || this.height)
+			return h || Math.max(h, toPx(this.canvasHeight));
 		},
-		// #endif
-		// #ifdef VUE2
-		destroyed() {
-			this.done = false
-			this.inited = false
-			this.firstRender = 0
+		hasBoard() {
+			return this.board && Object.keys(this.board).length
+		},
+		elements() {
+			return this.hasBoard ? this.board : JSON.parse(JSON.stringify(this.el))
+		}
+	},
+	created() {
+		this.use2dCanvas = this.type === '2d' && canIUseCanvas2d() && !isPC
+	},
+	async mounted() {
+		await sleep(30)
+		await this.getParentWeith()
+		this.$nextTick(() => {
+			setTimeout(() => {
+				this.$watch('elements', this.watchRender, {
+					deep: true,
+					immediate: true
+				});
+			}, 30)
+		})
+	},
+	// #ifdef VUE3
+	unmounted() {
+		this.done = false
+		this.inited = false
+		this.firstRender = 0
+		this.progress = 0
+		this.painter = null
+		clearTimeout(this.rendertimer)
+	},
+	// #endif
+	// #ifdef VUE2
+	destroyed() {
+		this.done = false
+		this.inited = false
+		this.firstRender = 0
+		this.progress = 0
+		this.painter = null
+		clearTimeout(this.rendertimer)
+	},
+	// #endif
+	methods: {
+		async watchRender(val, old) {
+			if (!val || !val.views || (!this.firstRender ? !val.views.length : !this.firstRender) || !Object.keys(val).length || JSON.stringify(val) == JSON.stringify(old)) return;
+			this.firstRender = 1
 			this.progress = 0
-			this.painter = null
+			this.done = false
 			clearTimeout(this.rendertimer)
+			this.rendertimer = setTimeout(() => {
+				this.render(val);
+			}, this.beforeDelay)
 		},
-		// #endif
-		methods: {
-			async watchRender(val, old) {
-				if (!val || !val.views || (!this.firstRender ? !val.views.length : !this.firstRender) || !Object.keys(val).length || JSON.stringify(val) == JSON.stringify(old)) return;
-				this.firstRender = 1
-				this.progress = 0
-				this.done = false
-				clearTimeout(this.rendertimer)
-				this.rendertimer = setTimeout(() => {
-					this.render(val);
-				}, this.beforeDelay)
-			},
-			async setFilePath(path, param) {
-				let filePath = path
-				const {pathType = this.pathType} =  param || this
-				if (pathType == 'base64' && !isBase64(path)) {
-					filePath = await pathToBase64(path)
-				} else if (pathType == 'url' && isBase64(path)) {
-					filePath = await base64ToPath(path)
-				}
-				if (param && param.isEmit) {
-					this.$emit('success', filePath);
-				}
-				return filePath
-			},
-			async getSize(args) {
-				const {width} = args.css || args
-				const {height} = args.css || args
-				if (!this.size) {
-					if (width || height) {
-						this.canvasWidth = width || this.canvasWidth
-						this.canvasHeight = height || this.canvasHeight
-						await sleep(30);
-					} else {
-						await this.getParentWeith()
-					}
-				}
-			},
-			canvasToTempFilePathSync(args) {
-				// this.stopWatch && this.stopWatch()
-				// this.stopWatch = this.$watch('done', (v) => {
-				// 	if (v) {
-				// 		this.canvasToTempFilePath(args)
-				// 		this.stopWatch && this.stopWatch()
-				// 	}
-				// }, {
-				// 	immediate: true
-				// })
-				this.tasks.push(args)
-				if(this.done){
-					this.runTask()
-				}
-			},
-			runTask(){
-				while(this.tasks.length){
-					const task = this.tasks.shift()	
-					 this.canvasToTempFilePath(task)
+		async setFilePath(path, param) {
+			let filePath = path
+			const { pathType = this.pathType } = param || this
+			if (pathType == 'base64' && !isBase64(path)) {
+				filePath = await pathToBase64(path)
+			} else if (pathType == 'url' && isBase64(path)) {
+				filePath = await base64ToPath(path)
+			}
+			if (param && param.isEmit) {
+				this.$emit('success', filePath);
+			}
+			return filePath
+		},
+		async getSize(args) {
+			const { width } = args.css || args
+			const { height } = args.css || args
+			if (!this.size) {
+				if (width || height) {
+					this.canvasWidth = width || this.canvasWidth
+					this.canvasHeight = height || this.canvasHeight
+					await sleep(30);
+				} else {
+					await this.getParentWeith()
 				}
-			},
-			// #ifndef APP-NVUE
-			getParentWeith() {
-				return new Promise(resolve => {
-					uni.createSelectorQuery()
-						.in(this)
-						.select(`.lime-painter`)
-						.boundingClientRect()
-						.exec(res => {
-							const {width, height} = res[0]||{}
-							this.parentWidth = Math.ceil(width||0)
-							this.canvasWidth = this.parentWidth || 300
-							this.canvasHeight = height || this.canvasHeight||150
-							resolve(res[0])
-						})
-				})
-			},
-			async render(args = {}) {
-				if(!Object.keys(args).length) {
-					return console.error('空对象')
+			}
+		},
+		canvasToTempFilePathSync(args) {
+			// this.stopWatch && this.stopWatch()
+			// this.stopWatch = this.$watch('done', (v) => {
+			// 	if (v) {
+			// 		this.canvasToTempFilePath(args)
+			// 		this.stopWatch && this.stopWatch()
+			// 	}
+			// }, {
+			// 	immediate: true
+			// })
+			this.tasks.push(args)
+			if (this.done) {
+				this.runTask()
+			}
+		},
+		runTask() {
+			while (this.tasks.length) {
+				const task = this.tasks.shift()
+				this.canvasToTempFilePath(task)
+			}
+		},
+		// #ifndef APP-NVUE
+		getParentWeith() {
+			return new Promise(resolve => {
+				uni.createSelectorQuery()
+					.in(this)
+					.select(`.lime-painter`)
+					.boundingClientRect()
+					.exec(res => {
+						const { width, height } = res[0] || {}
+						this.parentWidth = Math.ceil(width || 0)
+						this.canvasWidth = this.parentWidth || 300
+						this.canvasHeight = height || this.canvasHeight || 150
+						resolve(res[0])
+					})
+			})
+		},
+		async render(args = {}) {
+			if (!Object.keys(args).length) {
+				return console.error('空对象')
+			}
+			this.progress = 0
+			this.done = false
+			// #ifdef APP-NVUE
+			this.tempFilePath.length = 0
+			// #endif
+			await this.getSize(args)
+			const ctx = await this.getContext();
+
+			let {
+				use2dCanvas,
+				boardWidth,
+				boardHeight,
+				canvas,
+				afterDelay
+			} = this;
+			if (use2dCanvas && !canvas) {
+				return Promise.reject(new Error('canvas 没创建'));
+			}
+			this.boundary = {
+				top: 0,
+				left: 0,
+				width: boardWidth,
+				height: boardHeight
+			};
+			this.painter = null
+			if (!this.painter) {
+				const { width } = args.css || args
+				const { height } = args.css || args
+				if (!width && this.parentWidth) {
+					Object.assign(args, { width: this.parentWidth })
 				}
-				this.progress = 0
-				this.done = false
-				// #ifdef APP-NVUE
-				this.tempFilePath.length = 0
-				// #endif
-				await this.getSize(args)
-				const ctx = await this.getContext();
-				
-				let {
-					use2dCanvas,
-					boardWidth,
-					boardHeight,
+				const param = {
+					context: ctx,
 					canvas,
-					afterDelay
-				} = this;
-				if (use2dCanvas && !canvas) {
-					return Promise.reject(new Error('canvas 没创建'));
-				}
-				this.boundary = {
-					top: 0,
-					left: 0,
 					width: boardWidth,
-					height: boardHeight
-				};
-				this.painter = null
-				if (!this.painter) {
-					const {width} = args.css || args
-					const {height} = args.css || args
-					if(!width && this.parentWidth) {
-						Object.assign(args, {width: this.parentWidth})
-					}
-					const param = {
-						context: ctx,
-						canvas,
-						width: boardWidth,
-						height: boardHeight,
-						pixelRatio: this.dpr,
-						useCORS: this.useCORS,
-						createImage: getImageInfo.bind(this),
-						performance: this.performance,
-						listen: {
-							onProgress: (v) => {
-								this.progress = v
-								this.$emit('progress', v)
-							},
-							onEffectFail: (err) => {
-								this.$emit('faill', err)
-							}
+					height: boardHeight,
+					pixelRatio: this.dpr,
+					useCORS: this.useCORS,
+					createImage: getImageInfo.bind(this),
+					performance: this.performance,
+					listen: {
+						onProgress: (v) => {
+							this.progress = v
+							this.$emit('progress', v)
+						},
+						onEffectFail: (err) => {
+							this.$emit('faill', err)
 						}
 					}
-					this.painter = new Painter(param)
-				} 
-				try{
-					// vue3 赋值给data会引起图片无法绘制
-					const { width, height } = await this.painter.source(JSON.parse(JSON.stringify(args)))
-					this.boundary.height = this.canvasHeight = height
-					this.boundary.width = this.canvasWidth = width
-					await sleep(this.sleep);
-					await this.painter.render()
-					await new Promise(resolve => this.$nextTick(resolve));
-					if (!use2dCanvas) {
-						await this.canvasDraw();
-					}
-					if (afterDelay && use2dCanvas) {
-						await sleep(afterDelay);
-					}
-					this.$emit('done');
-					this.done = true
-					if (this.isCanvasToTempFilePath) {
-						this.canvasToTempFilePath()
-							.then(res => {
-								this.$emit('success', res.tempFilePath)
-							})
-							.catch(err => {
-								this.$emit('fail', new Error(JSON.stringify(err)));
-							});
-					}
-					this.runTask()
-					return Promise.resolve({
-						ctx,
-						draw: this.painter,
-						node: this.node
-					});
-				}catch(e){
-					//TODO handle the exception
 				}
-				
-			},
-			canvasDraw(flag = false) {
-				return new Promise((resolve, reject) => this.ctx.draw(flag, () => setTimeout(() => resolve(), this
-					.afterDelay)));
-			},
-			async getContext() {
-				if (!this.canvasWidth) {
-					this.$emit('fail', 'painter no size')
-					console.error('[lime-painter]: 给画板或父级设置尺寸')
-					return Promise.reject();
+				this.painter = new Painter(param)
+			}
+			try {
+				// vue3 赋值给data会引起图片无法绘制
+				const { width, height } = await this.painter.source(JSON.parse(JSON.stringify(args)))
+				this.boundary.height = this.canvasHeight = height
+				this.boundary.width = this.canvasWidth = width
+				await sleep(this.sleep);
+				await this.painter.render()
+				await new Promise(resolve => this.$nextTick(resolve));
+				if (!use2dCanvas) {
+					await this.canvasDraw();
 				}
-				if (this.ctx && this.inited) {
-					return Promise.resolve(this.ctx);
+				if (afterDelay && use2dCanvas) {
+					await sleep(afterDelay);
 				}
-				const { type, use2dCanvas, dpr, boardWidth, boardHeight } = this;
-				const _getContext = () => {
-					return new Promise(resolve => {
-						uni.createSelectorQuery()
-							.in(this)
-							.select(`#${this.canvasId}`)
-							.boundingClientRect()
-							.exec(res => {
-								if (res) {
-									const ctx = uni.createCanvasContext(this.canvasId, this);
-									if (!this.inited) {
-										this.inited = true;
-										this.use2dCanvas = false;
-										this.canvas = res;
-									}
-									
-									// 钉钉小程序框架不支持 measureText 方法,用此方法 mock
-									if (!ctx.measureText) {
-										function strLen(str) {
-											let len = 0;
-											for (let i = 0; i < str.length; i++) {
-												if (str.charCodeAt(i) > 0 && str.charCodeAt(i) < 128) {
-													len++;
-												} else {
-													len += 2;
-												}
-											}
-											return len;
-										}
-										ctx.measureText = text => {
-											let fontSize = ctx.state && ctx.state.fontSize || 12;
-											const font = ctx.__font
-											if (font && fontSize == 12) {
-												fontSize = parseInt(font.split(' ')[3], 10);
-											}
-											fontSize /= 2;
-											return {
-												width: strLen(text) * fontSize
-											};
-										}
-									}
-									
-									// #ifdef MP-ALIPAY
-									ctx.scale(dpr, dpr);
-									// #endif
-									this.ctx = ctx
-									resolve(this.ctx);
-								} else {
-									console.error('[lime-painter] no node')
-								}
-							});
-					});
-				};
-				if (!use2dCanvas) {
-					return _getContext();
+				this.$emit('done');
+				this.done = true
+				if (this.isCanvasToTempFilePath) {
+					this.canvasToTempFilePath()
+						.then(res => {
+							this.$emit('success', res.tempFilePath)
+						})
+						.catch(err => {
+							this.$emit('fail', new Error(JSON.stringify(err)));
+						});
 				}
+				this.runTask()
+				return Promise.resolve({
+					ctx,
+					draw: this.painter,
+					node: this.node
+				});
+			} catch (e) {
+				//TODO handle the exception
+			}
+
+		},
+		canvasDraw(flag = false) {
+			return new Promise((resolve, reject) => this.ctx.draw(flag, () => setTimeout(() => resolve(), this
+				.afterDelay)));
+		},
+		async getContext() {
+			if (!this.canvasWidth) {
+				this.$emit('fail', 'painter no size')
+				console.error('[lime-painter]: 给画板或父级设置尺寸')
+				return Promise.reject();
+			}
+			if (this.ctx && this.inited) {
+				return Promise.resolve(this.ctx);
+			}
+			const { type, use2dCanvas, dpr, boardWidth, boardHeight } = this;
+			const _getContext = () => {
 				return new Promise(resolve => {
 					uni.createSelectorQuery()
 						.in(this)
 						.select(`#${this.canvasId}`)
-						.node()
+						.boundingClientRect()
 						.exec(res => {
-							let {node: canvas} = res && res[0]||{};
-							if(canvas) {
-								const ctx = canvas.getContext(type);
+							if (res) {
+								const ctx = uni.createCanvasContext(this.canvasId, this);
 								if (!this.inited) {
 									this.inited = true;
-									this.use2dCanvas = true;
-									this.canvas = canvas;
+									this.use2dCanvas = false;
+									this.canvas = res;
 								}
+
+								// 钉钉小程序框架不支持 measureText 方法,用此方法 mock
+								if (!ctx.measureText) {
+									function strLen(str) {
+										let len = 0;
+										for (let i = 0; i < str.length; i++) {
+											if (str.charCodeAt(i) > 0 && str.charCodeAt(i) < 128) {
+												len++;
+											} else {
+												len += 2;
+											}
+										}
+										return len;
+									}
+									ctx.measureText = text => {
+										let fontSize = ctx.state && ctx.state.fontSize || 12;
+										const font = ctx.__font
+										if (font && fontSize == 12) {
+											fontSize = parseInt(font.split(' ')[3], 10);
+										}
+										fontSize /= 2;
+										return {
+											width: strLen(text) * fontSize
+										};
+									}
+								}
+
+								// #ifdef MP-ALIPAY
+								ctx.scale(dpr, dpr);
+								// #endif
 								this.ctx = ctx
 								resolve(this.ctx);
 							} else {
-								console.error('[lime-painter]: no size')
+								console.error('[lime-painter] no node')
 							}
 						});
 				});
-			},
-			canvasToTempFilePath(args = {}) {
-				return new Promise(async (resolve, reject) => {
-					const { use2dCanvas, canvasId, dpr, fileType, quality } = this;
-					const success = async (res) => {
-						try {
-							const tempFilePath = await this.setFilePath(res.tempFilePath || res, args)
-							const result = Object.assign(res, {tempFilePath})
-							args.success && args.success(result)
-							resolve(result)
-						} catch (e) {
-							this.$emit('fail', e)
-						}
-					}
-					
-					let { top: y = 0, left: x = 0, width, height } = this.boundary || this;
-					// let destWidth = width * dpr;
-					// let destHeight = height * dpr;
-					// #ifdef MP-ALIPAY
-					// width = destWidth;
-					// height = destHeight;
-					// #endif
-					
-					const copyArgs = Object.assign({
-						// x,
-						// y,
-						// width,
-						// height,
-						// destWidth,
-						// destHeight,
-						canvasId,
-						id: canvasId,
-						fileType,
-						quality,
-					}, args, {success});
-					// if(this.isPC || use2dCanvas) {
-					// 	copyArgs.canvas = this.canvas
-					// }
-					if (use2dCanvas) {
-						copyArgs.canvas = this.canvas
-						try{
-							// #ifndef MP-ALIPAY
-							const oFilePath = this.canvas.toDataURL(`image/${args.fileType||fileType}`.replace(/pg/, 'peg'), args.quality||quality)
-							if(/data:,/.test(oFilePath)) {
-								uni.canvasToTempFilePath(copyArgs, this);
-							} else {
-								const tempFilePath = await this.setFilePath(oFilePath, args)
-								args.success && args.success({tempFilePath})
-								resolve({tempFilePath})
+			};
+			if (!use2dCanvas) {
+				return _getContext();
+			}
+			return new Promise(resolve => {
+				uni.createSelectorQuery()
+					.in(this)
+					.select(`#${this.canvasId}`)
+					.node()
+					.exec(res => {
+						let { node: canvas } = res && res[0] || {};
+						if (canvas) {
+							const ctx = canvas.getContext(type);
+							if (!this.inited) {
+								this.inited = true;
+								this.use2dCanvas = true;
+								this.canvas = canvas;
 							}
-							// #endif
-							// #ifdef MP-ALIPAY
-							this.canvas.toTempFilePath(copyArgs)
-							// #endif
-						}catch(e){
-							args.fail && args.fail(e)
-							reject(e)
+							this.ctx = ctx
+							resolve(this.ctx);
+						} else {
+							console.error('[lime-painter]: no size')
 						}
-					} else {
-						// #ifdef MP-ALIPAY
-						if(this.ctx.toTempFilePath) {
-							// 钉钉
-							const ctx = uni.createCanvasContext(canvasId);
-							ctx.toTempFilePath(copyArgs);
+					});
+			});
+		},
+		canvasToTempFilePath(args = {}) {
+			return new Promise(async (resolve, reject) => {
+				const { use2dCanvas, canvasId, dpr, fileType, quality } = this;
+				const success = async (res) => {
+					try {
+						const tempFilePath = await this.setFilePath(res.tempFilePath || res, args)
+						const result = Object.assign(res, { tempFilePath })
+						args.success && args.success(result)
+						resolve(result)
+					} catch (e) {
+						this.$emit('fail', e)
+					}
+				}
+
+				let { top: y = 0, left: x = 0, width, height } = this.boundary || this;
+				// let destWidth = width * dpr;
+				// let destHeight = height * dpr;
+				// #ifdef MP-ALIPAY
+				// width = destWidth;
+				// height = destHeight;
+				// #endif
+
+				const copyArgs = Object.assign({
+					// x,
+					// y,
+					// width,
+					// height,
+					// destWidth,
+					// destHeight,
+					canvasId,
+					id: canvasId,
+					fileType,
+					quality,
+				}, args, { success });
+				// if(this.isPC || use2dCanvas) {
+				// 	copyArgs.canvas = this.canvas
+				// }
+				if (use2dCanvas) {
+					copyArgs.canvas = this.canvas
+					try {
+						// #ifndef MP-ALIPAY
+						const oFilePath = this.canvas.toDataURL(`image/${args.fileType || fileType}`.replace(/pg/, 'peg'), args.quality || quality)
+						if (/data:,/.test(oFilePath)) {
+							uni.canvasToTempFilePath(copyArgs, this);
 						} else {
-							my.canvasToTempFilePath(copyArgs);
+							const tempFilePath = await this.setFilePath(oFilePath, args)
+							args.success && args.success({ tempFilePath })
+							resolve({ tempFilePath })
 						}
 						// #endif
-						// #ifndef MP-ALIPAY
-						uni.canvasToTempFilePath(copyArgs, this);
+						// #ifdef MP-ALIPAY
+						this.canvas.toTempFilePath(copyArgs)
 						// #endif
+					} catch (e) {
+						args.fail && args.fail(e)
+						reject(e)
 					}
-				})
-			}
-			// #endif
+				} else {
+					// #ifdef MP-ALIPAY
+					if (this.ctx.toTempFilePath) {
+						// 钉钉
+						const ctx = uni.createCanvasContext(canvasId);
+						ctx.toTempFilePath(copyArgs);
+					} else {
+						my.canvasToTempFilePath(copyArgs);
+					}
+					// #endif
+					// #ifndef MP-ALIPAY
+					uni.canvasToTempFilePath(copyArgs, this);
+					// #endif
+				}
+			})
 		}
-	};
-</script>
-<style>
-	.lime-painter,
-	.lime-painter__canvas {
-		// #ifndef APP-NVUE
-		width: 100%;
-		// #endif
-		// #ifdef APP-NVUE
-		flex: 1;
 		// #endif
 	}
+};
+</script>
+<style lang="scss">
+.lime-painter,
+.lime-painter__canvas {
+	// #ifndef APP-NVUE
+	width: 100%;
+	// #endif
+	// #ifdef APP-NVUE
+	flex: 1;
+	// #endif
+}
 </style>

File diff suppressed because it is too large
+ 82 - 48
uni_modules/lime-painter/components/lime-painter/lime-painter.vue


Some files were not shown because too many files changed in this diff