├── .gitignore
├── pages
├── post
│ ├── post.json
│ ├── post.wxss
│ ├── post.js
│ └── post.wxml
├── combine
│ ├── combine.wxss
│ ├── combine.json
│ ├── combine.wxml
│ └── combine.js
├── index
│ ├── index.json
│ ├── index.wxss
│ ├── index.wxml
│ └── index.js
├── share
│ ├── share.json
│ ├── share.wxss
│ ├── share.js
│ └── share.wxml
└── upload
│ ├── upload.json
│ ├── upload.wxml
│ ├── upload.wxss
│ └── upload.js
├── libs
├── wxa-plugin-canvas
│ ├── poster
│ │ ├── index.wxss
│ │ ├── index.json
│ │ ├── index.wxml
│ │ ├── poster.js
│ │ └── index.js
│ └── index
│ │ ├── index.json
│ │ ├── index.wxml
│ │ ├── index.wxss
│ │ └── index.js
├── colorui
│ ├── components
│ │ ├── cu-custom.wxss
│ │ ├── cu-custom.json
│ │ ├── cu-custom.wxml
│ │ └── cu-custom.js
│ └── animation.wxss
└── we-cropper
│ ├── we-cropper.wxml
│ ├── we-cropper.min.js
│ └── we-cropper.js
├── image
├── 1.png
├── 2.png
├── 3.png
├── 4.png
├── 5.png
├── 6.png
├── 7.png
├── 8.png
├── 9.png
├── bg.jpg
└── posters
│ ├── 1.jpg
│ ├── 2.jpg
│ ├── 3.jpg
│ └── 4.jpg
├── functions
└── imgSecCheckV2
│ ├── config.json
│ ├── package.json
│ └── index.js
├── sitemap.json
├── project.private.config.json
├── app.wxss
├── app.json
├── utils
└── util.js
├── README.md
├── app.js
├── project.config.json
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/pages/post/post.json:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/libs/wxa-plugin-canvas/poster/index.wxss:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/pages/combine/combine.wxss:
--------------------------------------------------------------------------------
1 | /* pages/combine/combine.wxss */
--------------------------------------------------------------------------------
/pages/index/index.json:
--------------------------------------------------------------------------------
1 | {
2 | "disableScroll": true
3 | }
--------------------------------------------------------------------------------
/libs/wxa-plugin-canvas/index/index.json:
--------------------------------------------------------------------------------
1 | {
2 | "component": true
3 | }
--------------------------------------------------------------------------------
/libs/colorui/components/cu-custom.wxss:
--------------------------------------------------------------------------------
1 | /* colorui/components/cu-custom.wxss */
--------------------------------------------------------------------------------
/image/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/1.png
--------------------------------------------------------------------------------
/image/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/2.png
--------------------------------------------------------------------------------
/image/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/3.png
--------------------------------------------------------------------------------
/image/4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/4.png
--------------------------------------------------------------------------------
/image/5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/5.png
--------------------------------------------------------------------------------
/image/6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/6.png
--------------------------------------------------------------------------------
/image/7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/7.png
--------------------------------------------------------------------------------
/image/8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/8.png
--------------------------------------------------------------------------------
/image/9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/9.png
--------------------------------------------------------------------------------
/image/bg.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/bg.jpg
--------------------------------------------------------------------------------
/libs/colorui/components/cu-custom.json:
--------------------------------------------------------------------------------
1 | {
2 | "component": true,
3 | "usingComponents": {}
4 | }
--------------------------------------------------------------------------------
/image/posters/1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/posters/1.jpg
--------------------------------------------------------------------------------
/image/posters/2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/posters/2.jpg
--------------------------------------------------------------------------------
/image/posters/3.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/posters/3.jpg
--------------------------------------------------------------------------------
/image/posters/4.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/idealclover/Wear-Bachelor-Cap/HEAD/image/posters/4.jpg
--------------------------------------------------------------------------------
/pages/share/share.json:
--------------------------------------------------------------------------------
1 | {
2 | "usingComponents": {
3 | "poster": "../../libs/wxa-plugin-canvas/poster"
4 | }
5 | }
--------------------------------------------------------------------------------
/pages/combine/combine.json:
--------------------------------------------------------------------------------
1 | {
2 | "usingComponents": {
3 | "poster": "../../libs/wxa-plugin-canvas/poster"
4 | }
5 | }
--------------------------------------------------------------------------------
/pages/post/post.wxss:
--------------------------------------------------------------------------------
1 | /* pages/share.wxss */
2 | button::after{
3 | border:0;
4 | }
5 | button{
6 | background-color: #fff;
7 | }
--------------------------------------------------------------------------------
/pages/share/share.wxss:
--------------------------------------------------------------------------------
1 | /* pages/share.wxss */
2 | button::after{
3 | border:0;
4 | }
5 | button{
6 | background-color: #fff;
7 | }
--------------------------------------------------------------------------------
/functions/imgSecCheckV2/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "permissions": {
3 | "openapi": [
4 | "security.imgSecCheck"
5 | ]
6 | }
7 | }
--------------------------------------------------------------------------------
/functions/imgSecCheckV2/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "wx-server-sdk": "latest",
4 | "axios": "0.27.2"
5 | }
6 | }
--------------------------------------------------------------------------------
/libs/wxa-plugin-canvas/poster/index.json:
--------------------------------------------------------------------------------
1 | {
2 | "component": true,
3 | "usingComponents": {
4 | "we-canvas": "../index/index"
5 | }
6 | }
--------------------------------------------------------------------------------
/libs/wxa-plugin-canvas/poster/index.wxml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/pages/upload/upload.json:
--------------------------------------------------------------------------------
1 | {
2 | "backgroundTextStyle":"dark",
3 | "navigationBarBackgroundColor": "#000",
4 | "navigationBarTitleText": "裁剪头像",
5 | "navigationBarTextStyle": "white"
6 | }
--------------------------------------------------------------------------------
/sitemap.json:
--------------------------------------------------------------------------------
1 | {
2 | "desc": "关于本文件的更多信息,请参考文档 https://developers.weixin.qq.com/miniprogram/dev/framework/sitemap.html",
3 | "rules": [{
4 | "action": "allow",
5 | "page": "*"
6 | }]
7 | }
--------------------------------------------------------------------------------
/libs/wxa-plugin-canvas/index/index.wxml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/project.private.config.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档:https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html",
3 | "projectname": "Wear-Bachelor-Cap",
4 | "setting": {
5 | "compileHotReLoad": true
6 | }
7 | }
--------------------------------------------------------------------------------
/app.wxss:
--------------------------------------------------------------------------------
1 | /**app.wxss**/
2 |
3 | /* @import './libs/weui-miniprogram/weui-wxss/dist/style/weui.wxss'; */
4 | @import "./libs/colorui/main.wxss";
5 | @import "./libs/colorui/icon.wxss";
6 |
7 | .footer {
8 | margin-top: 10px;
9 | margin-bottom: 5px;
10 | }
11 |
12 | .footer-item {
13 | height: 38rpx;
14 | }
15 |
--------------------------------------------------------------------------------
/libs/wxa-plugin-canvas/index/index.wxss:
--------------------------------------------------------------------------------
1 | .canvas {
2 | width: 750rpx;
3 | height: 750rpx;
4 | }
5 | .canvas.pro {
6 | position: absolute;
7 | bottom: 0;
8 | left: 0;
9 | transform: translate3d(-9999rpx, 0, 0);
10 | }
11 | .canvas.debug {
12 | position: absolute;
13 | bottom: 0;
14 | left: 0;
15 | border: 1rpx solid #ccc;
16 | }
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "pages": [
3 | "pages/index/index",
4 | "pages/combine/combine",
5 | "pages/upload/upload",
6 | "pages/share/share",
7 | "pages/post/post"
8 | ],
9 | "window": {
10 | "backgroundTextStyle": "light",
11 | "navigationBarBackgroundColor": "#E54D42",
12 | "navigationBarTitleText": "毕业帽头像",
13 | "navigationBarTextStyle": "white"
14 | },
15 | "sitemapLocation": "sitemap.json"
16 | }
--------------------------------------------------------------------------------
/utils/util.js:
--------------------------------------------------------------------------------
1 | const formatTime = date => {
2 | const year = date.getFullYear()
3 | const month = date.getMonth() + 1
4 | const day = date.getDate()
5 | const hour = date.getHours()
6 | const minute = date.getMinutes()
7 | const second = date.getSeconds()
8 |
9 | return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
10 | }
11 |
12 | const formatNumber = n => {
13 | n = n.toString()
14 | return n[1] ? n : '0' + n
15 | }
16 |
17 | module.exports = {
18 | formatTime: formatTime
19 | }
20 |
--------------------------------------------------------------------------------
/libs/we-cropper/we-cropper.wxml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
17 |
--------------------------------------------------------------------------------
/pages/upload/upload.wxml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | 重新选择
8 |
9 |
10 |
11 | 确定
12 |
13 |
14 |
--------------------------------------------------------------------------------
/libs/wxa-plugin-canvas/poster/poster.js:
--------------------------------------------------------------------------------
1 | const defaultOptions = {
2 | selector: '#poster'
3 | };
4 |
5 | function Poster(options = {}, that) {
6 | options = {
7 | ...defaultOptions,
8 | ...options,
9 | };
10 |
11 | const pages = getCurrentPages();
12 | let ctx = pages[pages.length - 1];
13 | if (that) ctx = that
14 | const poster = ctx.selectComponent(options.selector);
15 | delete options.selector;
16 |
17 | return poster;
18 | };
19 |
20 | Poster.create = (reset = false, that) => {
21 | const poster = Poster({}, that);
22 | if (!poster) {
23 | console.error('请设置组件的id="poster"!!!');
24 | } else {
25 | return Poster({}, that).onCreate(reset);
26 | }
27 | }
28 |
29 | export default Poster;
30 |
--------------------------------------------------------------------------------
/libs/colorui/components/cu-custom.wxml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/libs/colorui/components/cu-custom.js:
--------------------------------------------------------------------------------
1 | const app = getApp();
2 | Component({
3 | /**
4 | * 组件的一些选项
5 | */
6 | options: {
7 | addGlobalClass: true,
8 | multipleSlots: true
9 | },
10 | /**
11 | * 组件的对外属性
12 | */
13 | properties: {
14 | bgColor: {
15 | type: String,
16 | default: ''
17 | },
18 | isCustom: {
19 | type: [Boolean, String],
20 | default: false
21 | },
22 | isBack: {
23 | type: [Boolean, String],
24 | default: false
25 | },
26 | bgImage: {
27 | type: String,
28 | default: ''
29 | },
30 | },
31 | /**
32 | * 组件的初始数据
33 | */
34 | data: {
35 | StatusBar: app.globalData.StatusBar,
36 | CustomBar: app.globalData.CustomBar,
37 | Custom: app.globalData.Custom
38 | },
39 | /**
40 | * 组件的方法列表
41 | */
42 | methods: {
43 | BackPage() {
44 | wx.navigateBack({
45 | delta: 1
46 | });
47 | },
48 | toHome(){
49 | wx.reLaunch({
50 | url: '/pages/index/index',
51 | })
52 | }
53 | }
54 | })
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 毕业帽头像生成
2 |
3 | > 🎓️ 没有毕业典礼只能整整活
4 |
5 | 采用微信小程序编写 实现了为头像戴上毕业帽的功能
6 |
7 | 基于 [我要戴口罩 idealclover/Wear-A-Mask](https://github.com/idealclover/Wear-A-Mask)
8 |
9 | ## 扫码预览
10 |
11 | 
12 |
13 | ## 小程序截图
14 |
15 | 
16 |
17 | ## 生成头像示例
18 |
19 | 
20 |
21 | ## 海报示例
22 |
23 | 
24 |
25 | ## 项目依赖
26 |
27 | * [jasscia/ChristmasHat](https://github.com/jasscia/ChristmasHat)
28 | * [Tencent/weui-wxss](https://github.com/Tencent/weui-wxss)
29 | * [jasondu/wxa-plugin-canvas](https://github.com/jasondu/wxa-plugin-canvas)
30 |
31 | ## 相关项目
32 |
33 | * [我要戴口罩 idealclover/Wear-A-Mask](https://github.com/idealclover/Wear-A-Mask)
34 |
35 | ## LICENSE
36 |
37 | 所有代码根据 [GPL-3.0](./LICENSE) 协议。换句话说,如果您在本项目基础上进行二次开发,需将项目以同样协议进行开源。
38 |
39 | 设计资源制作特殊感谢:@spencerwooo ovoclover lockoff(排名不分先后)
40 |
--------------------------------------------------------------------------------
/pages/upload/upload.wxss:
--------------------------------------------------------------------------------
1 | .cropper-wrapper {
2 | flex-direction: row;
3 | justify-content: space-between;
4 | align-items: center;
5 | height: 100%;
6 | background-color: #e5e5e5;
7 | }
8 |
9 | /* .cropper-buttons{
10 | display: flex;
11 | flex-direction: row;
12 | justify-content: space-between;
13 | align-items: center;
14 | position: absolute;
15 | bottom: 0;
16 | left: 0;
17 | width: 100%;
18 | height: 50px;
19 | padding: 0 20rpx;
20 | box-sizing: border-box;
21 | line-height: 50px;
22 | } */
23 |
24 | .cropper-buttons {
25 | display: flex;
26 | position: absolute;
27 | justify-content: space-between;
28 | align-items: center;
29 | bottom: 0;
30 | padding: 0 20rpx;
31 | width: 100%;
32 | }
33 |
34 | /* .cropper-buttons .upload, .cropper-buttons .getCropperImage{
35 | text-align: center;
36 | } */
37 |
38 | .cropper {
39 | position: absolute;
40 | top: 0;
41 | left: 0;
42 | }
43 |
44 | .cropper-buttons{
45 | background-color: rgba(0, 0, 0, 0.95);
46 | }
47 |
48 | /* .btn{
49 | height: 30px;
50 | line-height: 30px;
51 | padding: 0 24rpx;
52 | border-radius: 2px;
53 | color: #ffffff;
54 | } */
55 |
--------------------------------------------------------------------------------
/app.js:
--------------------------------------------------------------------------------
1 | //app.js
2 | App({
3 | onLaunch: function () {
4 | // 展示本地存储能力
5 | var logs = wx.getStorageSync('logs') || []
6 | logs.unshift(Date.now())
7 | wx.setStorageSync('logs', logs)
8 |
9 | // 登录
10 | wx.login({
11 | success: res => {
12 | // 发送 res.code 到后台换取 openId, sessionKey, unionId
13 | }
14 | })
15 | // 获取用户信息
16 | wx.getSetting({
17 | success: res => {
18 | if (res.authSetting['scope.userInfo']) {
19 | // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
20 | wx.getUserInfo({
21 | success: res => {
22 | // 可以将 res 发送给后台解码出 unionId
23 | this.globalData.userInfo = res.userInfo
24 |
25 | // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
26 | // 所以此处加入 callback 以防止这种情况
27 | if (this.userInfoReadyCallback) {
28 | this.userInfoReadyCallback(res)
29 | }
30 | }
31 | })
32 | }
33 | }
34 | })
35 | },
36 | globalData: {
37 | userInfo: null,
38 | bgPic:null,
39 | scale:1,
40 | rotate:0,
41 | hat_center_x:0,
42 | hat_center_x:0,
43 | currentHatId:1
44 | }
45 | })
--------------------------------------------------------------------------------
/pages/index/index.wxss:
--------------------------------------------------------------------------------
1 | /* pages/index/index.wxss */
2 |
3 | .btnZoom {
4 | position: relative;
5 | width: 100%;
6 | height: 300px;
7 | }
8 |
9 | .bgPic, .emptyBg {
10 | background-color: #eee;
11 | height: 300px;
12 | width: 300px;
13 | }
14 |
15 | .hat {
16 | height: 100px;
17 | width: 100px;
18 | position: absolute;
19 | border: dashed 2px yellow;
20 | top: 100px;
21 | }
22 |
23 | .handle, .cancel {
24 | position: absolute;
25 | z-index: 1;
26 | width: 20px;
27 | height: 20px;
28 | background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAv0lEQVQ4jb2TYQ3DIBCFKwEJSEACEpBQCZVQB0ioBCRUQiUgAQnffuyRsK2QrWlGcmnC8d67e3edprsPYIAFOIAMFCAB8xCkrxcwAk5kRvercu6MIDfgMBBywFYF20SpJFf7LopdKlWpjT65+qxAI0AEgmIF0i8Vba0X8uf/BFFAr71IylmFGRF4LU8bszw6eJ7ydUVv5E4jp1f656a9VpY1mdx7UNS/1UitVKP2JOjtuQfNz7RL7ZAHy9C4q+cByTtkeikNbOoAAAAASUVORK5CYII=);
29 | background-repeat: no-repeat;
30 | background-position: center;
31 | border-radius: 10px;
32 | background-color: #39b94a;
33 | }
34 |
35 | .scrollView {
36 | width: 100%;
37 | /* position: absolute;
38 | bottom: 5px; */
39 | white-space: nowrap;
40 | }
41 |
42 | .imgList {
43 | height: 70px;
44 | width: 70px;
45 | border: 2px solid;
46 | border-color: #eee;
47 | margin: 5px;
48 | }
49 |
--------------------------------------------------------------------------------
/functions/imgSecCheckV2/index.js:
--------------------------------------------------------------------------------
1 | // 云函数入口文件
2 | const cloud = require('wx-server-sdk');
3 | const axios = require('axios');
4 |
5 | cloud.init({
6 | env: cloud.DYNAMIC_CURRENT_ENV
7 | })
8 |
9 | exports.main = async (event, context) => {
10 | try {
11 | let buffer = null;
12 | await axios({
13 | method: 'get',
14 | url: event.file,
15 | responseType: 'arraybuffer',
16 | headers: {
17 | "Content-Type": "*"
18 | }
19 | }).then(res => {
20 | buffer = res.data;
21 | });
22 |
23 | const result = await cloud.openapi.security.imgSecCheck({
24 | media: {
25 | contentType: 'image/png',
26 | value: buffer
27 | }
28 | })
29 | if (result && result.errCode.toString() === '87014') {
30 | return {
31 | code: 500,
32 | msg: '内容含有违法违规内容',
33 | data: result
34 | }
35 | } else {
36 | return {
37 | code: 200,
38 | msg: '内容ok',
39 | data: result
40 | }
41 | }
42 | } catch (err) {
43 | console.log(err)
44 | // 错误处理
45 | if (err.errCode.toString() === '87014') {
46 | return {
47 | code: 500,
48 | msg: '内容含有违法违规内容',
49 | data: err
50 | }
51 | }
52 | return {
53 | code: 502,
54 | msg: '调用imgSecCheck接口异常',
55 | data: err
56 | }
57 | }
58 | }
--------------------------------------------------------------------------------
/pages/post/post.js:
--------------------------------------------------------------------------------
1 | // pages/share.js
2 | const app = getApp();
3 |
4 | Page({
5 | /**
6 | * 页面的初始数据
7 | */
8 | data: {
9 | swiperList: [],
10 | },
11 | savePic() {
12 | let swiperList = this.data.swiperList;
13 | let taskList = [];
14 | for (let i = 0; i < swiperList.length; i++) {
15 | taskList.push(new Promise((resolve, reject) => {
16 | wx.saveImageToPhotosAlbum({
17 | filePath: swiperList[i].url,
18 | success: resolve(),
19 | fail: reject()
20 | });
21 | }))
22 | }
23 | Promise.all(taskList).then(res => {
24 | wx.navigateTo({
25 | url: "../share/share"
26 | });
27 | })
28 | },
29 | notSavePic() {
30 | wx.navigateTo({
31 | url: "../share/share"
32 | });
33 | },
34 | onLoad: function() {
35 | let successPic = app.globalData.successPic ?
36 | app.globalData.successPic : "https://image.idealclover.cn/projects/Wear-Bachelor-Cap/avatar.jpg";
37 | console.log(app.globalData.posters);
38 | this.setData({
39 | swiperList: app.globalData.posters
40 | })
41 | },
42 |
43 | /**
44 | * 用户点击右上角分享
45 | */
46 | onShareAppMessage: function() {
47 | let successPic = app.globalData.successPic ?
48 | app.globalData.successPic : "https://image.idealclover.cn/projects/Wear-Bachelor-Cap/avatar_share.jpg";
49 | return {
50 | title: "戴上学士帽,我们毕业啦!",
51 | imageUrl: successPic,
52 | path: "/pages/index/index",
53 | success: function(res) {}
54 | };
55 | }
56 | });
--------------------------------------------------------------------------------
/pages/post/post.wxml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 | 不保存海报
15 |
16 |
17 |
28 |
29 |
30 |
31 | Copyright © 2018-2020
32 |
33 |
34 |
35 |
36 | idealclover
37 |
38 |
39 |
40 |
41 | 谨以此小程序献给我的母校南京大学
42 |
43 |
44 |
--------------------------------------------------------------------------------
/pages/combine/combine.wxml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | z
5 |
15 |
16 |
17 |
18 |
19 |
30 |
31 |
32 | Copyright © 2018-2020
33 |
34 |
35 |
36 |
37 | idealclover
38 |
39 |
40 |
41 |
42 | 谨以此小程序献给我的母校南京大学
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/pages/share/share.js:
--------------------------------------------------------------------------------
1 | // pages/share.js
2 | const app = getApp();
3 |
4 | Page({
5 | /**
6 | * 页面的初始数据
7 | */
8 | data: {
9 | actionSheetHidden: true,
10 | },
11 | actionSheetTap: function() {
12 | this.setData({
13 | actionSheetHidden: !this.data.actionSheetHidden
14 | })
15 | },
16 | listenerActionSheet: function() {
17 | this.setData({
18 | actionSheetHidden: !this.data.actionSheetHidden
19 | })
20 | },
21 | onLoad: function() {
22 | let successPic = app.globalData.successPic ?
23 | app.globalData.successPic :
24 | "https://image.idealclover.cn/projects/Wear-Bachelor-Cap/avatar.jpg";
25 | // : "https://idealclover.top/icon.jpg";
26 | const posterConfig = {
27 | width: 840,
28 | height: 1280,
29 | backgroundColor: "#fff",
30 | debug: false,
31 | pixelRatio: 1,
32 | blocks: [],
33 | texts: [],
34 | images: [{
35 | width: 840,
36 | height: 1280,
37 | x: 0,
38 | y: 0,
39 | borderRadius: 0,
40 | url: "https://image.idealclover.cn/projects/Wear-Bachelor-Cap/bg.png"
41 | },
42 | {
43 | width: 670,
44 | height: 670,
45 | x: 85,
46 | y: 211,
47 | url: successPic
48 | },
49 | ]
50 | };
51 | this.setData({
52 | posterConfig: posterConfig
53 | });
54 | },
55 |
56 | onPosterSuccess(e) {
57 | const {
58 | detail
59 | } = e;
60 | wx.previewImage({
61 | current: detail,
62 | urls: [detail]
63 | });
64 | },
65 | onPosterFail(err) {
66 | console.error(err);
67 | },
68 |
69 | /**
70 | * 用户点击右上角分享
71 | */
72 | onShareAppMessage: function() {
73 | let successPic = app.globalData.successPic ?
74 | app.globalData.successPic :
75 | "https://image.idealclover.cn/projects/Wear-Bachelor-Cap/avatar_share.jpg";
76 | return {
77 | title: "戴上学士帽,我们毕业啦!",
78 | imageUrl: successPic,
79 | path: "/pages/index/index",
80 | success: function(res) {}
81 | };
82 | }
83 | });
--------------------------------------------------------------------------------
/project.config.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "项目配置文件",
3 | "packOptions": {
4 | "ignore": [
5 | {
6 | "value": "README.md",
7 | "type": "file"
8 | }
9 | ],
10 | "include": []
11 | },
12 | "setting": {
13 | "urlCheck": false,
14 | "es6": true,
15 | "enhance": true,
16 | "postcss": true,
17 | "preloadBackgroundData": false,
18 | "minified": true,
19 | "newFeature": true,
20 | "coverView": true,
21 | "nodeModules": false,
22 | "autoAudits": false,
23 | "showShadowRootInWxmlPanel": true,
24 | "scopeDataCheck": false,
25 | "uglifyFileName": false,
26 | "checkInvalidKey": true,
27 | "checkSiteMap": true,
28 | "uploadWithSourceMap": true,
29 | "compileHotReLoad": false,
30 | "lazyloadPlaceholderEnable": false,
31 | "useMultiFrameRuntime": true,
32 | "useApiHook": true,
33 | "useApiHostProcess": true,
34 | "babelSetting": {
35 | "ignore": [],
36 | "disablePlugins": [],
37 | "outputPath": ""
38 | },
39 | "useIsolateContext": false,
40 | "userConfirmedBundleSwitch": false,
41 | "packNpmManually": false,
42 | "packNpmRelationList": [],
43 | "minifyWXSS": true,
44 | "disableUseStrict": false,
45 | "minifyWXML": true,
46 | "showES6CompileOption": false,
47 | "useCompilerPlugins": false,
48 | "ignoreUploadUnusedFiles": true,
49 | "condition": false
50 | },
51 | "compileType": "miniprogram",
52 | "libVersion": "2.19.2",
53 | "appid": "wx04ff92a861325b05",
54 | "projectname": "Wear-Bachelor-Cap",
55 | "cloudfunctionRoot": "functions/",
56 | "simulatorType": "wechat",
57 | "simulatorPluginLibVersion": {},
58 | "cloudfunctionTemplateRoot": "cloudfunctionTemplate/",
59 | "condition": {
60 | "miniprogram": {
61 | "list": [
62 | {
63 | "name": "pages/share/share",
64 | "pathName": "pages/share/share",
65 | "query": "",
66 | "scene": null
67 | },
68 | {
69 | "name": "pages/post/post",
70 | "pathName": "pages/post/post",
71 | "query": "",
72 | "scene": null
73 | }
74 | ]
75 | }
76 | },
77 | "editorSetting": {
78 | "tabIndent": "insertSpaces",
79 | "tabSize": 2
80 | }
81 | }
--------------------------------------------------------------------------------
/pages/share/share.wxml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | 保存成功
8 |
9 |
10 | 生成的头像已经保存到相册 OωO
11 |
12 |
15 |
16 | 去发个朋友圈!
17 |
18 |
19 |
22 |
23 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 | 取消
46 |
47 |
48 |
49 |
50 | Copyright © 2018-2020
51 |
52 |
53 |
54 |
55 | idealclover
56 |
57 |
58 |
59 |
60 | 谨以此小程序献给我的母校南京大学
61 |
62 |
--------------------------------------------------------------------------------
/pages/index/index.wxml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | 点击授权登录加载您的头像
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
36 |
37 |
38 | Copyright © 2018-2020
39 |
40 |
41 |
42 | idealclover
43 |
44 |
45 |
46 |
47 | 谨以此小程序献给我的母校南京大学
48 |
--------------------------------------------------------------------------------
/libs/wxa-plugin-canvas/poster/index.js:
--------------------------------------------------------------------------------
1 | Component({
2 | properties: {
3 | config: {
4 | type: Object,
5 | value: {},
6 | },
7 | preload: { // 是否预下载图片资源
8 | type: Boolean,
9 | value: false,
10 | },
11 | hideLoading: { // 是否隐藏loading
12 | type: Boolean,
13 | value: false,
14 | }
15 | },
16 | ready() {
17 | if (this.data.preload) {
18 | const poster = this.selectComponent('#poster');
19 | this.downloadStatus = 'doing';
20 | poster.downloadResource(this.data.config).then(() => {
21 | this.downloadStatus = 'success';
22 | this.trigger('downloadSuccess');
23 | }).catch((e) => {
24 | this.downloadStatus = 'fail';
25 | this.trigger('downloadFail', e);
26 | });
27 | }
28 | },
29 | methods: {
30 | trigger(event, data) {
31 | if (this.listener && typeof this.listener[event] === 'function') {
32 | this.listener[event](data);
33 | }
34 | },
35 | once(event, fun) {
36 | if (typeof this.listener === 'undefined') {
37 | this.listener = {};
38 | }
39 | this.listener[event] = fun;
40 | },
41 | downloadResource(reset) {
42 | return new Promise((resolve, reject) => {
43 | if (reset) {
44 | this.downloadStatus = null;
45 | }
46 | const poster = this.selectComponent('#poster');
47 | if (this.downloadStatus && this.downloadStatus !== 'fail') {
48 | if (this.downloadStatus === 'success') {
49 | resolve();
50 | } else {
51 | this.once('downloadSuccess', () => resolve());
52 | this.once('downloadFail', (e) => reject(e));
53 | }
54 | } else {
55 | poster.downloadResource(this.data.config)
56 | .then(() => {
57 | this.downloadStatus = 'success';
58 | resolve();
59 | })
60 | .catch((e) => reject(e));
61 | }
62 | })
63 | },
64 | onCreate(reset = false) {
65 | !this.data.hideLoading && wx.showLoading({ mask: true, title: '生成中' });
66 | return this.downloadResource(typeof reset === 'boolean' && reset).then(() => {
67 | !this.data.hideLoading && wx.hideLoading();
68 | const poster = this.selectComponent('#poster');
69 | poster.create(this.data.config);
70 | })
71 | .catch((err) => {
72 | !this.data.hideLoading && wx.hideLoading();
73 | wx.showToast({ icon: 'none', title: err.errMsg || '生成失败' });
74 | console.error(err);
75 | this.triggerEvent('fail', err);
76 | })
77 | },
78 | onCreateSuccess(e) {
79 | const { detail } = e;
80 | this.triggerEvent('success', detail);
81 | },
82 | onCreateFail(err) {
83 | console.error(err);
84 | this.triggerEvent('fail', err);
85 | }
86 | }
87 | })
--------------------------------------------------------------------------------
/libs/colorui/animation.wxss:
--------------------------------------------------------------------------------
1 | /*
2 | Animation 微动画
3 | 基于ColorUI组建库的动画模块 by 文晓港 2019年3月26日19:52:28
4 | */
5 |
6 | /* css 滤镜 控制黑白底色gif的 */
7 | .gif-black{
8 | mix-blend-mode: screen;
9 | }
10 | .gif-white{
11 | mix-blend-mode: multiply;
12 | }
13 |
14 |
15 | /* Animation css */
16 | [class*=animation-] {
17 | animation-duration: .5s;
18 | animation-timing-function: ease-out;
19 | animation-fill-mode: both
20 | }
21 |
22 | .animation-fade {
23 | animation-name: fade;
24 | animation-duration: .8s;
25 | animation-timing-function: linear
26 | }
27 |
28 | .animation-scale-up {
29 | animation-name: scale-up
30 | }
31 |
32 | .animation-scale-down {
33 | animation-name: scale-down
34 | }
35 |
36 | .animation-slide-top {
37 | animation-name: slide-top
38 | }
39 |
40 | .animation-slide-bottom {
41 | animation-name: slide-bottom
42 | }
43 |
44 | .animation-slide-left {
45 | animation-name: slide-left
46 | }
47 |
48 | .animation-slide-right {
49 | animation-name: slide-right
50 | }
51 |
52 | .animation-shake {
53 | animation-name: shake
54 | }
55 |
56 | .animation-reverse {
57 | animation-direction: reverse
58 | }
59 |
60 | @keyframes fade {
61 | 0% {
62 | opacity: 0
63 | }
64 |
65 | 100% {
66 | opacity: 1
67 | }
68 | }
69 |
70 | @keyframes scale-up {
71 | 0% {
72 | opacity: 0;
73 | transform: scale(.2)
74 | }
75 |
76 | 100% {
77 | opacity: 1;
78 | transform: scale(1)
79 | }
80 | }
81 |
82 | @keyframes scale-down {
83 | 0% {
84 | opacity: 0;
85 | transform: scale(1.8)
86 | }
87 |
88 | 100% {
89 | opacity: 1;
90 | transform: scale(1)
91 | }
92 | }
93 |
94 | @keyframes slide-top {
95 | 0% {
96 | opacity: 0;
97 | transform: translateY(-100%)
98 | }
99 |
100 | 100% {
101 | opacity: 1;
102 | transform: translateY(0)
103 | }
104 | }
105 |
106 | @keyframes slide-bottom {
107 | 0% {
108 | opacity: 0;
109 | transform: translateY(100%)
110 | }
111 |
112 | 100% {
113 | opacity: 1;
114 | transform: translateY(0)
115 | }
116 | }
117 |
118 | @keyframes shake {
119 |
120 | 0%,
121 | 100% {
122 | transform: translateX(0)
123 | }
124 |
125 | 10% {
126 | transform: translateX(-9px)
127 | }
128 |
129 | 20% {
130 | transform: translateX(8px)
131 | }
132 |
133 | 30% {
134 | transform: translateX(-7px)
135 | }
136 |
137 | 40% {
138 | transform: translateX(6px)
139 | }
140 |
141 | 50% {
142 | transform: translateX(-5px)
143 | }
144 |
145 | 60% {
146 | transform: translateX(4px)
147 | }
148 |
149 | 70% {
150 | transform: translateX(-3px)
151 | }
152 |
153 | 80% {
154 | transform: translateX(2px)
155 | }
156 |
157 | 90% {
158 | transform: translateX(-1px)
159 | }
160 | }
161 |
162 | @keyframes slide-left {
163 | 0% {
164 | opacity: 0;
165 | transform: translateX(-100%)
166 | }
167 |
168 | 100% {
169 | opacity: 1;
170 | transform: translateX(0)
171 | }
172 | }
173 |
174 | @keyframes slide-right {
175 | 0% {
176 | opacity: 0;
177 | transform: translateX(100%)
178 | }
179 |
180 | 100% {
181 | opacity: 1;
182 | transform: translateX(0)
183 | }
184 | }
--------------------------------------------------------------------------------
/pages/combine/combine.js:
--------------------------------------------------------------------------------
1 | // pages/combine/combine.js
2 | import Poster from "../../libs/wxa-plugin-canvas/poster/poster"
3 | const app = getApp();
4 | Page({
5 | data: {
6 | posters: [],
7 | successNum: 0,
8 | posterConfig: {}
9 | },
10 |
11 | onLoad: function (options) {
12 | wx.getImageInfo({
13 | src: app.globalData.bgPic,
14 | success: res => {
15 | this.bgPic = res.path;
16 | console.log(this.bgPic)
17 | this.draw();
18 | }
19 | });
20 | },
21 |
22 | /**
23 | * 生命周期函数--监听页面初次渲染完成
24 | */
25 | onReady: function () {},
26 |
27 | draw() {
28 | let scale = app.globalData.scale;
29 | let rotate = app.globalData.rotate;
30 | let hat_center_x = app.globalData.hat_center_x;
31 | let hat_center_y = app.globalData.hat_center_y;
32 | let currentHatId = app.globalData.currentHatId;
33 | const pc = wx.createCanvasContext("myCanvas");
34 | const hat_size = 100 * scale;
35 |
36 | pc.clearRect(0, 0, 300, 300);
37 | pc.drawImage(this.bgPic, 0, 0, 300, 300);
38 | pc.translate(hat_center_x, hat_center_y);
39 | pc.rotate((rotate * Math.PI) / 180);
40 | pc.drawImage(
41 | "../../image/" + currentHatId + ".png", -hat_size / 2, -hat_size / 2,
42 | hat_size,
43 | hat_size
44 | );
45 | pc.draw();
46 | },
47 | savePic() {
48 | wx.showLoading({
49 | mask: true,
50 | title: '生成中'
51 | })
52 | wx.canvasToTempFilePath({
53 | x: 0,
54 | y: 0,
55 | height: 300,
56 | width: 300,
57 | canvasId: "myCanvas",
58 | success: res => {
59 | app.globalData.successPic = res.tempFilePath;
60 | wx.saveImageToPhotosAlbum({
61 | filePath: res.tempFilePath,
62 | success: res => {
63 | this.onPosterSuccess({
64 | detail: 'start'
65 | });
66 | // console.log("success:" + res);
67 | },
68 | fail(e) {
69 | console.log("err:" + e);
70 | }
71 | });
72 | }
73 | });
74 | },
75 | onPosterSuccess(e) {
76 | const {
77 | detail
78 | } = e;
79 | console.log(detail)
80 | const successNum = this.data.successNum;
81 | if (detail != 'start') this.data.posters = this.data.posters.concat([{
82 | id: successNum,
83 | url: detail
84 | }]);
85 | if (successNum >= 4) {
86 | app.globalData.posters = this.data.posters;
87 | console.log(app.globalData.posters);
88 | wx.hideLoading();
89 | wx.navigateTo({
90 | url: "../post/post"
91 | });
92 | } else {
93 | this.setData({
94 | successNum: successNum + 1,
95 | posterConfig: {
96 | width: 1240,
97 | height: 1754,
98 | backgroundColor: "#fff",
99 | debug: false,
100 | pixelRatio: 1,
101 | blocks: [],
102 | texts: [],
103 | images: [{
104 | width: 1240,
105 | height: 1754,
106 | x: 0,
107 | y: 0,
108 | borderRadius: 0,
109 | url: "/image/posters/" + (successNum + 1) + ".jpg"
110 | },
111 | {
112 | width: 656,
113 | height: 656,
114 | x: 292,
115 | y: 246,
116 | url: app.globalData.successPic
117 | },
118 | ]
119 | }
120 | }, () => {
121 | setTimeout(function () {
122 | Poster.create(true);
123 | }, 50)
124 | });
125 | }
126 | },
127 | /**
128 | * 用户点击右上角分享
129 | */
130 | onShareAppMessage: function () {
131 | let successPic = app.globalData.successPic ?
132 | app.globalData.successPic :
133 | "https://image.idealclover.cn/projects/Wear-Bachelor-Cap/avatar_share.jpg";
134 | return {
135 | title: "戴上学士帽,我们毕业啦!!",
136 | imageUrl: successPic,
137 | path: "/pages/index/index",
138 | success: function (res) {}
139 | };
140 | }
141 | });
--------------------------------------------------------------------------------
/pages/upload/upload.js:
--------------------------------------------------------------------------------
1 | import WeCropper from '../../libs/we-cropper/we-cropper.js'
2 |
3 | const app = getApp()
4 | const config = app.globalData.config
5 |
6 | const device = wx.getSystemInfoSync()
7 | const width = device.windowWidth
8 | const height = device.windowHeight - 50
9 |
10 | Page({
11 | data: {
12 | cropperOpt: {
13 | id: 'cropper',
14 | targetId: 'targetCropper',
15 | pixelRatio: device.pixelRatio,
16 | width,
17 | height,
18 | scale: 2.5,
19 | zoom: 8,
20 | cut: {
21 | x: (width - 300) / 2,
22 | y: (height - 300) / 2,
23 | width: 300,
24 | height: 300
25 | },
26 | boundStyle: {
27 | color: '#8799A3',
28 | mask: 'rgba(0,0,0,0.8)',
29 | lineWidth: 1
30 | }
31 | }
32 | },
33 | touchStart(e) {
34 | this.cropper.touchStart(e)
35 | },
36 | touchMove(e) {
37 | this.cropper.touchMove(e)
38 | },
39 | touchEnd(e) {
40 | this.cropper.touchEnd(e)
41 | },
42 | getCropperImage() {
43 | this.cropper.getCropperImage(function (path, err) {
44 | wx.showLoading({
45 | title: '图片处理中',
46 | })
47 | if (err) {
48 | wx.showModal({
49 | title: '错误提示',
50 | content: err.message
51 | })
52 | } else {
53 | wx.cloud.init()
54 | wx.compressImage({
55 | src: path,
56 | quality: 50,
57 | fail: function () {
58 | wx.showToast({
59 | title: '文件识别失败',
60 | icon: 'none',
61 | duration: 2000
62 | })
63 | },
64 | success: res => {
65 | wx.cloud.callFunction({
66 | name: 'imgSecCheckV2',
67 | data: {
68 | file: wx.cloud.CDN({
69 | type: 'filePath',
70 | filePath: res.tempFilePath,
71 | })
72 | }
73 | }).then(result => {
74 | let {
75 | errCode
76 | } = result.result.data;
77 | switch (errCode) {
78 | case 87014:
79 | wx.showToast({
80 | title: '违法违规内容',
81 | icon: 'none',
82 | duration: 2000
83 | })
84 | break;
85 | case 0:
86 | // 获取裁剪图片资源后,给data添加src属性及其值
87 | let pages = getCurrentPages();
88 | let prevPage = pages[pages.length - 2];
89 | prevPage.setData({
90 | bgPic: path,
91 | picChoosed: true
92 | })
93 | wx.navigateBack({
94 | delta: 1
95 | })
96 | break;
97 | default:
98 | wx.showToast({
99 | title: '内部服务错误',
100 | icon: 'none',
101 | duration: 2000
102 | })
103 | break;
104 | }
105 | })
106 | }
107 | });
108 | }
109 | })
110 | },
111 | uploadTap() {
112 | const self = this
113 | wx.chooseImage({
114 | count: 1, // 默认9
115 | sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
116 | sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
117 | success(res) {
118 | const src = res.tempFilePaths[0]
119 | // 获取裁剪图片资源后,给data添加src属性及其值
120 | self.cropper.pushOrign(src)
121 | }
122 | })
123 | },
124 | onLoad(option) {
125 | const {
126 | cropperOpt
127 | } = this.data
128 |
129 | cropperOpt.boundStyle.color = '#8799A3'
130 |
131 | this.setData({
132 | cropperOpt
133 | })
134 |
135 | if (option.src) {
136 | cropperOpt.src = option.src
137 | this.cropper = new WeCropper(cropperOpt)
138 | // .on('ready', (ctx) => {
139 | // console.log(`wecropper is ready for work!`)
140 | // })
141 | // .on('beforeImageLoad', (ctx) => {
142 | // console.log(`before picture loaded, i can do something`)
143 | // console.log(`current canvas context:`, ctx)
144 | // wx.showToast({
145 | // title: '上传中',
146 | // icon: 'loading',
147 | // duration: 20000
148 | // })
149 | // })
150 | // .on('imageLoad', (ctx) => {
151 | // console.log(`picture loaded`)
152 | // console.log(`current canvas context:`, ctx)
153 | // wx.hideToast()
154 | // })
155 | // .on('beforeDraw', (ctx, instance) => {
156 | // console.log(`before canvas draw,i can do something`)
157 | // console.log(`current canvas context:`, ctx)
158 | // })
159 | }
160 | }
161 | })
--------------------------------------------------------------------------------
/pages/index/index.js:
--------------------------------------------------------------------------------
1 | // pages/index/index.js
2 | const app = getApp();
3 |
4 | Page({
5 | /**
6 | * 页面的初始数据
7 | */
8 | data: {
9 | bgPic: null,
10 | picChoosed: false,
11 | imgList: [1,2,3,4,5,6,7,8,9],
12 | currentHatId: 1,
13 | hatCenterX: 150,
14 | hatCenterY: 150,
15 | hatSize: 100,
16 | // cancelCenterX: wx.getSystemInfoSync().windowWidth / 2 - 50 - 2,
17 | // cancelCenterY: 100,
18 | handleCenterX: 201,
19 | handleCenterY: 200,
20 | scale: 1,
21 | rotate: 0
22 | },
23 | onReady() {
24 | this.getAvatar();
25 | this.hat_center_x = this.data.hatCenterX;
26 | this.hat_center_y = this.data.hatCenterY;
27 | // this.cancel_center_x = this.data.cancelCenterX;
28 | // this.cancel_center_y = this.data.cancelCenterY;
29 | this.handle_center_x = this.data.handleCenterX;
30 | this.handle_center_y = this.data.handleCenterY;
31 |
32 | this.scale = this.data.scale;
33 | this.rotate = this.data.rotate;
34 |
35 | this.touch_target = "";
36 | this.start_x = 0;
37 | this.start_y = 0;
38 | },
39 | assignPicChoosed() {
40 | if (this.data.bgPic) {
41 | this.setData({
42 | picChoosed: true
43 | });
44 | } else {
45 | this.setData({
46 | picChoosed: false
47 | });
48 | }
49 | },
50 | getAvatar() {
51 | wx.getUserProfile({
52 | desc: '用于获取当前用户头像', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
53 | success: (res) => {
54 | app.globalData.userInfo = res.userInfo;
55 | this.setData({
56 | userInfo: res.userInfo,
57 | bgPic: res.userInfo.avatarUrl.replace(/132/g, '0')
58 | });
59 | this.assignPicChoosed();
60 | }
61 | })
62 | },
63 | chooseImage(from) {
64 | wx.chooseImage({
65 | count: 1,
66 | sizeType: ["original", "compressed"],
67 | sourceType: ['album', 'camera'],
68 | success: res => {
69 | let src = res.tempFilePaths;
70 | wx.navigateTo({
71 | url: `../upload/upload?src=${src}`
72 | })
73 | },
74 | complete: res => {
75 | this.assignPicChoosed();
76 | }
77 | });
78 | },
79 | chooseImg(e) {
80 | this.setData({
81 | currentHatId: e.target.dataset.hatId
82 | });
83 | },
84 | touchStart(e) {
85 | if (e.target.id == "hat") {
86 | this.touch_target = "hat";
87 | } else if (e.target.id == "handle") {
88 | this.touch_target = "handle";
89 | } else {
90 | this.touch_target = "";
91 | }
92 |
93 | if (this.touch_target != "") {
94 | this.start_x = e.touches[0].clientX;
95 | this.start_y = e.touches[0].clientY;
96 | }
97 | },
98 | touchEnd(e) {
99 | this.hat_center_x = this.data.hatCenterX;
100 | this.hat_center_y = this.data.hatCenterY;
101 | // this.cancel_center_x = this.data.cancelCenterX;
102 | // this.cancel_center_y = this.data.cancelCenterY;
103 | this.handle_center_x = this.data.handleCenterX;
104 | this.handle_center_y = this.data.handleCenterY;
105 | // }
106 | this.touch_target = "";
107 | this.scale = this.data.scale;
108 | this.rotate = this.data.rotate;
109 | },
110 | touchMove(e) {
111 | var current_x = e.touches[0].clientX;
112 | var current_y = e.touches[0].clientY;
113 | var moved_x = current_x - this.start_x;
114 | var moved_y = current_y - this.start_y;
115 | if (this.touch_target == "hat") {
116 | this.setData({
117 | hatCenterX: this.data.hatCenterX + moved_x,
118 | hatCenterY: this.data.hatCenterY + moved_y,
119 | // cancelCenterX: this.data.cancelCenterX + moved_x,
120 | // cancelCenterY: this.data.cancelCenterY + moved_y,
121 | handleCenterX: this.data.handleCenterX + moved_x,
122 | handleCenterY: this.data.handleCenterY + moved_y
123 | });
124 | }
125 | if (this.touch_target == "handle") {
126 | this.setData({
127 | handleCenterX: this.data.handleCenterX + moved_x,
128 | handleCenterY: this.data.handleCenterY + moved_y,
129 | // cancelCenterX: 2 * this.data.hatCenterX - this.data.handleCenterX,
130 | // cancelCenterY: 2 * this.data.hatCenterY - this.data.handleCenterY
131 | });
132 | let diff_x_before = this.handle_center_x - this.hat_center_x;
133 | let diff_y_before = this.handle_center_y - this.hat_center_y;
134 | let diff_x_after = this.data.handleCenterX - this.hat_center_x;
135 | let diff_y_after = this.data.handleCenterY - this.hat_center_y;
136 | let distance_before = Math.sqrt(
137 | diff_x_before * diff_x_before + diff_y_before * diff_y_before
138 | );
139 | let distance_after = Math.sqrt(
140 | diff_x_after * diff_x_after + diff_y_after * diff_y_after
141 | );
142 | let angle_before =
143 | (Math.atan2(diff_y_before, diff_x_before) / Math.PI) * 180;
144 | let angle_after =
145 | (Math.atan2(diff_y_after, diff_x_after) / Math.PI) * 180;
146 | this.setData({
147 | scale: (distance_after / distance_before) * this.scale,
148 | rotate: angle_after - angle_before + this.rotate
149 | });
150 | }
151 | this.start_x = current_x;
152 | this.start_y = current_y;
153 | },
154 | combinePic() {
155 | app.globalData.bgPic = this.data.bgPic;
156 | app.globalData.scale = this.scale;
157 | app.globalData.rotate = this.rotate;
158 | app.globalData.hat_center_x = this.hat_center_x;
159 | app.globalData.hat_center_y = this.hat_center_y;
160 | app.globalData.currentHatId = this.data.currentHatId;
161 | wx.navigateTo({
162 | url: "../combine/combine"
163 | });
164 | },
165 | /**
166 | * 用户点击右上角分享
167 | */
168 | onShareAppMessage: function() {
169 | let successPic = app.globalData.successPic
170 | ? app.globalData.successPic
171 | : "https://image.idealclover.cn/projects/Wear-Bachelor-Cap/avatar_share.jpg";
172 | return {
173 | title: "戴上学士帽,我们毕业啦!",
174 | imageUrl: successPic,
175 | path: "/pages/index/index",
176 | success: function(res) {}
177 | };
178 | }
179 | });
180 |
--------------------------------------------------------------------------------
/libs/we-cropper/we-cropper.min.js:
--------------------------------------------------------------------------------
1 | /**
2 | * we-cropper v1.3.9
3 | * (c) 2020 dlhandsome
4 | * @license MIT
5 | */
6 | !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.WeCropper=e()}(this,function(){"use strict";var t=void 0,e=["touchstarted","touchmoved","touchended"];function r(n){for(var o=[],t=arguments.length-1;0>18&63)+d.charAt(r>>12&63)+d.charAt(r>>6&63)+d.charAt(63&r);return 2==a?(e=t.charCodeAt(c)<<8,n=t.charCodeAt(++c),i+=d.charAt((r=e+n)>>10)+d.charAt(r>>4&63)+d.charAt(r<<2&63)+"="):1==a&&(r=t.charCodeAt(c),i+=d.charAt(r>>2)+d.charAt(r<<4&63)+"=="),i},decode:function(t){var e=(t=String(t).replace(c,"")).length;e%4==0&&(e=(t=t.replace(/==?$/,"")).length),(e%4==1||/[^+a-zA-Z0-9/]/.test(t))&&s("Invalid character: the string to be decoded is not correctly encoded.");for(var n,o,r=0,a="",i=-1;++i>(-2*r&6)));return a},version:"0.1.0"};if(e&&!e.nodeType)if(n)n.exports=a;else for(var i in a)a.hasOwnProperty(i)&&(e[i]=a[i]);else t.base64=a}(f)});function x(t){var e="";if("string"==typeof t)e=t;else for(var n=0;n>8&255,r>>16&255,r>>24&255,0,0,0,0,54,0,0,0],i=[40,0,0,0,255&e,e>>8&255,e>>16&255,e>>24&255,255&n,n>>8&255,n>>16&255,n>>24&255,1,0,24,0,0,0,0,0,255&o,o>>8&255,o>>16&255,o>>24&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],c=(4-3*e%4)%4,u=t.data,s="",d=e<<2,h=n,f=String.fromCharCode;do{for(var l=d*(h-1),g="",p=0;p=h&&(p.newScale=h),p.scaleWidth=Math.round(p.newScale*p.baseWidth),p.scaleHeight=Math.round(p.newScale*p.baseHeight);var l=Math.round(p.touchX1-p.scaleWidth/2),g=Math.round(p.touchY1-p.scaleHeight/2);p.outsideBound(l,g),p.updateCanvas()},p.__xtouchEnd=function(){p.oldScale=p.newScale,p.rectX=p.imgLeft,p.rectY=p.imgTop})},C});
--------------------------------------------------------------------------------
/libs/wxa-plugin-canvas/index/index.js:
--------------------------------------------------------------------------------
1 | const main = {
2 | /**
3 | * 渲染块
4 | * @param {Object} params
5 | */
6 | drawBlock({ text, width = 0, height, x, y, paddingLeft = 0, paddingRight = 0, borderWidth, backgroundColor, borderColor, borderRadius = 0, opacity = 1 }) {
7 | // 判断是否块内有文字
8 | let blockWidth = 0; // 块的宽度
9 | let textX = 0;
10 | let textY = 0;
11 | if (typeof text !== 'undefined') {
12 | // 如果有文字并且块的宽度小于文字宽度,块的宽度为 文字的宽度 + 内边距
13 | const textWidth = this._getTextWidth(typeof text.text === 'string' ? text : text.text);
14 | blockWidth = textWidth > width ? textWidth : width;
15 | blockWidth += paddingLeft + paddingLeft;
16 |
17 | const { textAlign = 'left', text: textCon } = text;
18 | textY = height / 2 + y; // 文字的y轴坐标在块中线
19 | if (textAlign === 'left') {
20 | // 如果是右对齐,那x轴在块的最左边
21 | textX = x + paddingLeft;
22 | } else if (textAlign === 'center') {
23 | textX = blockWidth / 2 + x;
24 | } else {
25 | textX = x + blockWidth - paddingRight;
26 | }
27 | } else {
28 | blockWidth = width;
29 | }
30 |
31 | if (backgroundColor) {
32 | // 画面
33 | this.ctx.save();
34 | this.ctx.setGlobalAlpha(opacity);
35 | this.ctx.setFillStyle(backgroundColor);
36 | if (borderRadius > 0) {
37 | // 画圆角矩形
38 | this._drawRadiusRect(x, y, blockWidth, height, borderRadius);
39 | this.ctx.fill();
40 | } else {
41 | this.ctx.fillRect(this.toPx(x), this.toPx(y), this.toPx(blockWidth), this.toPx(height));
42 | }
43 | this.ctx.restore();
44 | }
45 | if (borderWidth) {
46 | // 画线
47 | this.ctx.save();
48 | this.ctx.setGlobalAlpha(opacity);
49 | this.ctx.setStrokeStyle(borderColor);
50 | this.ctx.setLineWidth(this.toPx(borderWidth));
51 | if (borderRadius > 0) {
52 | // 画圆角矩形边框
53 | this._drawRadiusRect(x, y, blockWidth, height, borderRadius);
54 | this.ctx.stroke();
55 | } else {
56 | this.ctx.strokeRect(this.toPx(x), this.toPx(y), this.toPx(blockWidth), this.toPx(height));
57 | }
58 | this.ctx.restore();
59 | }
60 |
61 | if (text) {
62 | this.drawText(Object.assign(text, { x: textX, y: textY }))
63 | }
64 | },
65 |
66 | /**
67 | * 渲染文字
68 | * @param {Object} params
69 | */
70 | drawText(params) {
71 | const { x, y, fontSize, color, baseLine, textAlign, text, opacity = 1, width, lineNum, lineHeight } = params;
72 | if (Object.prototype.toString.call(text) === '[object Array]') {
73 | let preText = { x, y, baseLine };
74 | text.forEach(item => {
75 | preText.x += item.marginLeft || 0;
76 | const textWidth = this._drawSingleText(Object.assign(item, {
77 | ...preText,
78 | }));
79 | preText.x += textWidth + (item.marginRight || 0); // 下一段字的x轴为上一段字x + 上一段字宽度
80 | })
81 | } else {
82 | this._drawSingleText(params);
83 | }
84 | },
85 |
86 | /**
87 | * 渲染图片
88 | */
89 | drawImage(data) {
90 | const { imgPath, x, y, w, h, sx, sy, sw, sh, borderRadius = 0, borderWidth = 0, borderColor } = data;
91 | this.ctx.save();
92 | if (borderRadius > 0) {
93 | this._drawRadiusRect(x, y, w, h, borderRadius);
94 | this.ctx.strokeStyle = 'rgba(255,255,255,0)';
95 | this.ctx.stroke();
96 | this.ctx.clip();
97 | this.ctx.drawImage(imgPath, this.toPx(sx), this.toPx(sy), this.toPx(sw), this.toPx(sh), this.toPx(x), this.toPx(y), this.toPx(w), this.toPx(h));
98 | if (borderWidth > 0) {
99 | this.ctx.setStrokeStyle(borderColor);
100 | this.ctx.setLineWidth(this.toPx(borderWidth));
101 | this.ctx.stroke();
102 | }
103 | } else {
104 | this.ctx.drawImage(imgPath, this.toPx(sx), this.toPx(sy), this.toPx(sw), this.toPx(sh), this.toPx(x), this.toPx(y), this.toPx(w), this.toPx(h));
105 | }
106 | this.ctx.restore();
107 | },
108 | /**
109 | * 渲染线
110 | * @param {*} param0
111 | */
112 | drawLine({ startX, startY, endX, endY, color, width }) {
113 | this.ctx.save();
114 | this.ctx.beginPath();
115 | this.ctx.setStrokeStyle(color);
116 | this.ctx.setLineWidth(this.toPx(width));
117 | this.ctx.moveTo(this.toPx(startX), this.toPx(startY));
118 | this.ctx.lineTo(this.toPx(endX), this.toPx(endY));
119 | this.ctx.stroke();
120 | this.ctx.closePath();
121 | this.ctx.restore();
122 | },
123 | downloadResource({ images = [], pixelRatio = 1 }) {
124 | const drawList = [];
125 | this.drawArr = [];
126 | images.forEach((image, index) => drawList.push(this._downloadImageAndInfo(image, index, pixelRatio)));
127 | return Promise.all(drawList);
128 | },
129 | initCanvas(w, h, debug) {
130 | return new Promise((resolve) => {
131 | this.setData({
132 | pxWidth: this.toPx(w),
133 | pxHeight: this.toPx(h),
134 | debug,
135 | }, resolve);
136 | });
137 | }
138 | }
139 | const handle = {
140 | /**
141 | * 画圆角矩形
142 | */
143 | _drawRadiusRect(x, y, w, h, r) {
144 | const br = r / 2;
145 | this.ctx.beginPath();
146 | this.ctx.moveTo(this.toPx(x + br), this.toPx(y)); // 移动到左上角的点
147 | this.ctx.lineTo(this.toPx(x + w - br), this.toPx(y));
148 | this.ctx.arc(this.toPx(x + w - br), this.toPx(y + br), this.toPx(br), 2 * Math.PI * (3 / 4), 2 * Math.PI * (4 / 4))
149 | this.ctx.lineTo(this.toPx(x + w), this.toPx(y + h - br));
150 | this.ctx.arc(this.toPx(x + w - br), this.toPx(y + h - br), this.toPx(br), 0, 2 * Math.PI * (1 / 4))
151 | this.ctx.lineTo(this.toPx(x + br), this.toPx(y + h));
152 | this.ctx.arc(this.toPx(x + br), this.toPx(y + h - br), this.toPx(br), 2 * Math.PI * (1 / 4), 2 * Math.PI * (2 / 4))
153 | this.ctx.lineTo(this.toPx(x), this.toPx(y + br));
154 | this.ctx.arc(this.toPx(x + br), this.toPx(y + br), this.toPx(br), 2 * Math.PI * (2 / 4), 2 * Math.PI * (3 / 4))
155 | },
156 | /**
157 | * 计算文本长度
158 | * @param {Array|Object}} text 数组 或者 对象
159 | */
160 | _getTextWidth(text) {
161 | let texts = [];
162 | if (Object.prototype.toString.call(text) === '[object Object]') {
163 | texts.push(text);
164 | } else {
165 | texts = text;
166 | }
167 | let width = 0;
168 | texts.forEach(({ fontSize, text, marginLeft = 0, marginRight = 0 }) => {
169 | this.ctx.setFontSize(this.toPx(fontSize));
170 | width += this.ctx.measureText(text).width + marginLeft + marginRight;
171 | })
172 |
173 | return this.toRpx(width);
174 | },
175 | /**
176 | * 渲染一段文字
177 | */
178 | _drawSingleText({ x, y, fontSize, color, baseLine, textAlign = 'left', text, opacity = 1, textDecoration = 'none',
179 | width, lineNum = 1, lineHeight = 0, fontWeight = 'normal', fontStyle = 'normal', fontFamily = "sans-serif"}) {
180 | this.ctx.save();
181 | this.ctx.beginPath();
182 | this.ctx.font = fontStyle + " " + fontWeight + " " + this.toPx(fontSize, true) + "px " + fontFamily
183 | this.ctx.setGlobalAlpha(opacity);
184 | // this.ctx.setFontSize(this.toPx(fontSize));
185 | this.ctx.setFillStyle(color);
186 | this.ctx.setTextBaseline(baseLine);
187 | this.ctx.setTextAlign(textAlign);
188 | let textWidth = this.toRpx(this.ctx.measureText(text).width);
189 | const textArr = [];
190 | if (textWidth > width) {
191 | // 文本宽度 大于 渲染宽度
192 | let fillText = '';
193 | let line = 1;
194 | for (let i = 0; i <= text.length - 1 ; i++) { // 将文字转为数组,一行文字一个元素
195 | fillText = fillText + text[i];
196 | if (this.toRpx(this.ctx.measureText(fillText).width) >= width) {
197 | if (line === lineNum) {
198 | if (i !== text.length - 1) {
199 | fillText = fillText.substring(0, fillText.length - 1) + '...';
200 | }
201 | }
202 | if(line <= lineNum) {
203 | textArr.push(fillText);
204 | }
205 | fillText = '';
206 | line++;
207 | } else {
208 | if(line <= lineNum) {
209 | if(i === text.length -1){
210 | textArr.push(fillText);
211 | }
212 | }
213 | }
214 | }
215 | textWidth = width;
216 | } else {
217 | textArr.push(text);
218 | }
219 |
220 | textArr.forEach((item, index) => {
221 | this.ctx.fillText(item, this.toPx(x), this.toPx(y + (lineHeight || fontSize) * index));
222 | })
223 |
224 | this.ctx.restore();
225 |
226 | // textDecoration
227 | if (textDecoration !== 'none') {
228 | let lineY = y;
229 | if (textDecoration === 'line-through') {
230 | // 目前只支持贯穿线
231 | lineY = y;
232 |
233 | // 小程序画布baseLine偏移阈值
234 | let threshold = 5;
235 |
236 | // 根据baseLine的不同对贯穿线的Y坐标做相应调整
237 | switch (baseLine) {
238 | case 'top':
239 | lineY += fontSize / 2 + threshold;
240 | break;
241 | case 'middle':
242 | break;
243 | case 'bottom':
244 | lineY -= fontSize / 2 + threshold;
245 | break;
246 | default:
247 | lineY -= fontSize / 2 - threshold;
248 | break;
249 | }
250 | }
251 | this.ctx.save();
252 | this.ctx.moveTo(this.toPx(x), this.toPx(lineY));
253 | this.ctx.lineTo(this.toPx(x) + this.toPx(textWidth), this.toPx(lineY));
254 | this.ctx.setStrokeStyle(color);
255 | this.ctx.stroke();
256 | this.ctx.restore();
257 | }
258 |
259 | return textWidth;
260 | },
261 | }
262 | const helper = {
263 | /**
264 | * 下载图片并获取图片信息
265 | */
266 | _downloadImageAndInfo(image, index, pixelRatio) {
267 | return new Promise((resolve, reject) => {
268 | const { x, y, url, zIndex } = image;
269 | const imageUrl = url;
270 | // 下载图片
271 | this._downImage(imageUrl, index)
272 | // 获取图片信息
273 | .then(imgPath => this._getImageInfo(imgPath, index))
274 | .then(({ imgPath, imgInfo }) => {
275 | // 根据画布的宽高计算出图片绘制的大小,这里会保证图片绘制不变形
276 | let sx;
277 | let sy;
278 | const borderRadius = image.borderRadius || 0;
279 | const setWidth = image.width;
280 | const setHeight = image.height;
281 | const width = this.toRpx(imgInfo.width / pixelRatio);
282 | const height = this.toRpx(imgInfo.height / pixelRatio);
283 |
284 | if (width / height <= setWidth / setHeight) {
285 | sx = 0;
286 | sy = (height - ((width / setWidth) * setHeight)) / 2;
287 | } else {
288 | sy = 0;
289 | sx = (width - ((height / setHeight) * setWidth)) / 2;
290 | }
291 | this.drawArr.push({
292 | type: 'image',
293 | borderRadius,
294 | borderWidth: image.borderWidth,
295 | borderColor: image.borderColor,
296 | zIndex: typeof zIndex !== 'undefined' ? zIndex : index,
297 | imgPath,
298 | sx,
299 | sy,
300 | sw: (width - (sx * 2)),
301 | sh: (height - (sy * 2)),
302 | x,
303 | y,
304 | w: setWidth,
305 | h: setHeight,
306 | });
307 | resolve();
308 | })
309 | .catch(err => reject(err));
310 | });
311 | },
312 | /**
313 | * 下载图片资源
314 | * @param {*} imageUrl
315 | */
316 | _downImage(imageUrl) {
317 | return new Promise((resolve, reject) => {
318 | if (/^http:\/\/tmp\//.test(imageUrl)) {
319 | resolve(imageUrl);
320 | } else if (
321 | /^http/.test(imageUrl) &&
322 | !new RegExp(wx.env.USER_DATA_PATH).test(imageUrl)
323 | ) {
324 | wx.downloadFile({
325 | url: this._mapHttpToHttps(imageUrl),
326 | success: res => {
327 | if (res.statusCode === 200) {
328 | resolve(res.tempFilePath);
329 | } else {
330 | reject(res.errMsg);
331 | }
332 | },
333 | fail(err) {
334 | reject(err);
335 | }
336 | });
337 | } else {
338 | // 支持本地地址
339 | resolve(imageUrl);
340 | }
341 | });
342 | },
343 | /**
344 | * 获取图片信息
345 | * @param {*} imgPath
346 | * @param {*} index
347 | */
348 | _getImageInfo(imgPath, index) {
349 | return new Promise((resolve, reject) => {
350 | wx.getImageInfo({
351 | src: imgPath,
352 | success(res) {
353 | resolve({ imgPath, imgInfo: res, index });
354 | },
355 | fail(err) {
356 | reject(err);
357 | },
358 | });
359 | });
360 | },
361 | toPx(rpx, int) {
362 | if (int) {
363 | return parseInt(rpx * this.factor * this.pixelRatio);
364 | }
365 | return rpx * this.factor * this.pixelRatio;
366 |
367 | },
368 | toRpx(px, int) {
369 | if (int) {
370 | return parseInt(px / this.factor);
371 | }
372 | return px / this.factor;
373 | },
374 | /**
375 | * 将http转为https
376 | * @param {String}} rawUrl 图片资源url
377 | */
378 | _mapHttpToHttps(rawUrl) {
379 | if (rawUrl.indexOf(':') < 0) {
380 | return rawUrl;
381 | }
382 | const urlComponent = rawUrl.split(':');
383 | if (urlComponent.length === 2) {
384 | if (urlComponent[0] === 'http') {
385 | urlComponent[0] = 'https';
386 | return `${urlComponent[0]}:${urlComponent[1]}`;
387 | }
388 | }
389 | return rawUrl;
390 | },
391 | }
392 | Component({
393 | properties: {
394 | },
395 | created() {
396 | const sysInfo = wx.getSystemInfoSync();
397 | const screenWidth = sysInfo.screenWidth;
398 | this.factor = screenWidth / 750;
399 | },
400 | methods: Object.assign({
401 | /**
402 | * 计算画布的高度
403 | * @param {*} config
404 | */
405 | getHeight(config) {
406 | const getTextHeight = (text) => {
407 | let fontHeight = text.lineHeight || text.fontSize;
408 | let height = 0;
409 | if (text.baseLine === 'top') {
410 | height = fontHeight;
411 | } else if (text.baseLine === 'middle') {
412 | height = fontHeight / 2;
413 | } else {
414 | height = 0;
415 | }
416 | return height;
417 | }
418 | const heightArr = [];
419 | (config.blocks || []).forEach((item) => {
420 | heightArr.push(item.y + item.height);
421 | });
422 | (config.texts || []).forEach((item) => {
423 | let height;
424 | if (Object.prototype.toString.call(item.text) === '[object Array]') {
425 | item.text.forEach((i) => {
426 | height = getTextHeight({...i, baseLine: item.baseLine});
427 | heightArr.push(item.y + height);
428 | });
429 | } else {
430 | height = getTextHeight(item);
431 | heightArr.push(item.y + height);
432 | }
433 | });
434 | (config.images || []).forEach((item) => {
435 | heightArr.push(item.y + item.height);
436 | });
437 | (config.lines || []).forEach((item) => {
438 | heightArr.push(item.startY);
439 | heightArr.push(item.endY);
440 | });
441 | const sortRes = heightArr.sort((a, b) => b - a);
442 | let canvasHeight = 0;
443 | if (sortRes.length > 0) {
444 | canvasHeight = sortRes[0];
445 | }
446 | if (config.height < canvasHeight || !config.height) {
447 | return canvasHeight;
448 | } else {
449 | return config.height;
450 | }
451 | },
452 | create(config) {
453 | this.ctx = wx.createCanvasContext('canvasid', this);
454 |
455 | this.pixelRatio = config.pixelRatio || 1;
456 | const height = this.getHeight(config);
457 | this.initCanvas(config.width, height, config.debug)
458 | .then(() => {
459 | // 设置画布底色
460 | if (config.backgroundColor) {
461 | this.ctx.save();
462 | this.ctx.setFillStyle(config.backgroundColor);
463 | this.ctx.fillRect(0, 0, this.toPx(config.width), this.toPx(height));
464 | this.ctx.restore();
465 | }
466 | const { texts = [], images = [], blocks = [], lines = [] } = config;
467 | const queue = this.drawArr
468 | .concat(texts.map((item) => {
469 | item.type = 'text';
470 | item.zIndex = item.zIndex || 0;
471 | return item;
472 | }))
473 | .concat(blocks.map((item) => {
474 | item.type = 'block';
475 | item.zIndex = item.zIndex || 0;
476 | return item;
477 | }))
478 | .concat(lines.map((item) => {
479 | item.type = 'line';
480 | item.zIndex = item.zIndex || 0;
481 | return item;
482 | }));
483 | // 按照顺序排序
484 | queue.sort((a, b) => a.zIndex - b.zIndex);
485 |
486 | queue.forEach((item) => {
487 | if (item.type === 'image') {
488 | this.drawImage(item)
489 | } else if (item.type === 'text') {
490 | this.drawText(item)
491 | } else if (item.type === 'block') {
492 | this.drawBlock(item)
493 | } else if (item.type === 'line') {
494 | this.drawLine(item)
495 | }
496 | });
497 |
498 | const res = wx.getSystemInfoSync();
499 | const platform = res.platform;
500 | let time = 0;
501 | if (platform === 'android') {
502 | // 在安卓平台,经测试发现如果海报过于复杂在转换时需要做延时,要不然样式会错乱
503 | time = 300;
504 | }
505 | this.ctx.draw(false, () => {
506 | setTimeout(() => {
507 | wx.canvasToTempFilePath({
508 | canvasId: 'canvasid',
509 | success: (res) => {
510 | this.triggerEvent('success', res.tempFilePath);
511 | },
512 | fail: (err) => {
513 | this.triggerEvent('fail', err);
514 | },
515 | }, this);
516 | }, time);
517 | });
518 | })
519 | .catch((err) => {
520 | wx.showToast({ icon: 'none', title: err.errMsg || '生成失败' });
521 | console.error(err);
522 | });
523 | },
524 | }, main, handle, helper),
525 | });
526 |
527 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/libs/we-cropper/we-cropper.js:
--------------------------------------------------------------------------------
1 | /**
2 | * we-cropper v1.3.9
3 | * (c) 2020 dlhandsome
4 | * @license MIT
5 | */
6 | (function (global, factory) {
7 | typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
8 | typeof define === 'function' && define.amd ? define(factory) :
9 | (global.WeCropper = factory());
10 | }(this, (function () { 'use strict';
11 |
12 | var device = void 0;
13 | var TOUCH_STATE = ['touchstarted', 'touchmoved', 'touchended'];
14 |
15 | function firstLetterUpper (str) {
16 | return str.charAt(0).toUpperCase() + str.slice(1)
17 | }
18 |
19 | function setTouchState (instance) {
20 | var arg = [], len = arguments.length - 1;
21 | while ( len-- > 0 ) arg[ len ] = arguments[ len + 1 ];
22 |
23 | TOUCH_STATE.forEach(function (key, i) {
24 | if (arg[i] !== undefined) {
25 | instance[key] = arg[i];
26 | }
27 | });
28 | }
29 |
30 | function validator (instance, o) {
31 | Object.defineProperties(instance, o);
32 | }
33 |
34 | function getDevice () {
35 | if (!device) {
36 | device = wx.getSystemInfoSync();
37 | }
38 | return device
39 | }
40 |
41 | var tmp = {};
42 |
43 | var ref = getDevice();
44 | var pixelRatio = ref.pixelRatio;
45 |
46 | var DEFAULT = {
47 | id: {
48 | default: 'cropper',
49 | get: function get () {
50 | return tmp.id
51 | },
52 | set: function set (value) {
53 | if (typeof (value) !== 'string') {
54 | console.error(("id:" + value + " is invalid"));
55 | }
56 | tmp.id = value;
57 | }
58 | },
59 | width: {
60 | default: 750,
61 | get: function get () {
62 | return tmp.width
63 | },
64 | set: function set (value) {
65 | if (typeof (value) !== 'number') {
66 | console.error(("width:" + value + " is invalid"));
67 | }
68 | tmp.width = value;
69 | }
70 | },
71 | height: {
72 | default: 750,
73 | get: function get () {
74 | return tmp.height
75 | },
76 | set: function set (value) {
77 | if (typeof (value) !== 'number') {
78 | console.error(("height:" + value + " is invalid"));
79 | }
80 | tmp.height = value;
81 | }
82 | },
83 | pixelRatio: {
84 | default: pixelRatio,
85 | get: function get () {
86 | return tmp.pixelRatio
87 | },
88 | set: function set (value) {
89 | if (typeof (value) !== 'number') {
90 | console.error(("pixelRatio:" + value + " is invalid"));
91 | }
92 | tmp.pixelRatio = value;
93 | }
94 | },
95 | scale: {
96 | default: 2.5,
97 | get: function get () {
98 | return tmp.scale
99 | },
100 | set: function set (value) {
101 | if (typeof (value) !== 'number') {
102 | console.error(("scale:" + value + " is invalid"));
103 | }
104 | tmp.scale = value;
105 | }
106 | },
107 | zoom: {
108 | default: 5,
109 | get: function get () {
110 | return tmp.zoom
111 | },
112 | set: function set (value) {
113 | if (typeof (value) !== 'number') {
114 | console.error(("zoom:" + value + " is invalid"));
115 | } else if (value < 0 || value > 10) {
116 | console.error("zoom should be ranged in 0 ~ 10");
117 | }
118 | tmp.zoom = value;
119 | }
120 | },
121 | src: {
122 | default: '',
123 | get: function get () {
124 | return tmp.src
125 | },
126 | set: function set (value) {
127 | if (typeof (value) !== 'string') {
128 | console.error(("src:" + value + " is invalid"));
129 | }
130 | tmp.src = value;
131 | }
132 | },
133 | cut: {
134 | default: {},
135 | get: function get () {
136 | return tmp.cut
137 | },
138 | set: function set (value) {
139 | if (typeof (value) !== 'object') {
140 | console.error(("cut:" + value + " is invalid"));
141 | }
142 | tmp.cut = value;
143 | }
144 | },
145 | boundStyle: {
146 | default: {},
147 | get: function get () {
148 | return tmp.boundStyle
149 | },
150 | set: function set (value) {
151 | if (typeof (value) !== 'object') {
152 | console.error(("boundStyle:" + value + " is invalid"));
153 | }
154 | tmp.boundStyle = value;
155 | }
156 | },
157 | onReady: {
158 | default: null,
159 | get: function get () {
160 | return tmp.ready
161 | },
162 | set: function set (value) {
163 | tmp.ready = value;
164 | }
165 | },
166 | onBeforeImageLoad: {
167 | default: null,
168 | get: function get () {
169 | return tmp.beforeImageLoad
170 | },
171 | set: function set (value) {
172 | tmp.beforeImageLoad = value;
173 | }
174 | },
175 | onImageLoad: {
176 | default: null,
177 | get: function get () {
178 | return tmp.imageLoad
179 | },
180 | set: function set (value) {
181 | tmp.imageLoad = value;
182 | }
183 | },
184 | onBeforeDraw: {
185 | default: null,
186 | get: function get () {
187 | return tmp.beforeDraw
188 | },
189 | set: function set (value) {
190 | tmp.beforeDraw = value;
191 | }
192 | }
193 | };
194 |
195 | var ref$1 = getDevice();
196 | var windowWidth = ref$1.windowWidth;
197 |
198 | function prepare () {
199 | var self = this;
200 |
201 | // v1.4.0 版本中将不再自动绑定we-cropper实例
202 | self.attachPage = function () {
203 | var pages = getCurrentPages();
204 | // 获取到当前page上下文
205 | var pageContext = pages[pages.length - 1];
206 | // 把this依附在Page上下文的wecropper属性上,便于在page钩子函数中访问
207 | Object.defineProperty(pageContext, 'wecropper', {
208 | get: function get () {
209 | console.warn(
210 | 'Instance will not be automatically bound to the page after v1.4.0\n\n' +
211 | 'Please use a custom instance name instead\n\n' +
212 | 'Example: \n' +
213 | 'this.mycropper = new WeCropper(options)\n\n' +
214 | '// ...\n' +
215 | 'this.mycropper.getCropperImage()'
216 | );
217 | return self
218 | },
219 | configurable: true
220 | });
221 | };
222 |
223 | self.createCtx = function () {
224 | var id = self.id;
225 | var targetId = self.targetId;
226 |
227 | if (id) {
228 | self.ctx = self.ctx || wx.createCanvasContext(id);
229 | self.targetCtx = self.targetCtx || wx.createCanvasContext(targetId);
230 | } else {
231 | console.error("constructor: create canvas context failed, 'id' must be valuable");
232 | }
233 | };
234 |
235 | self.deviceRadio = windowWidth / 750;
236 | }
237 |
238 | var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
239 |
240 |
241 |
242 |
243 |
244 | function createCommonjsModule(fn, module) {
245 | return module = { exports: {} }, fn(module, module.exports), module.exports;
246 | }
247 |
248 | var tools = createCommonjsModule(function (module, exports) {
249 | /**
250 | * String type check
251 | */
252 | exports.isStr = function (v) { return typeof v === 'string'; };
253 | /**
254 | * Number type check
255 | */
256 | exports.isNum = function (v) { return typeof v === 'number'; };
257 | /**
258 | * Array type check
259 | */
260 | exports.isArr = Array.isArray;
261 | /**
262 | * undefined type check
263 | */
264 | exports.isUndef = function (v) { return v === undefined; };
265 |
266 | exports.isTrue = function (v) { return v === true; };
267 |
268 | exports.isFalse = function (v) { return v === false; };
269 | /**
270 | * Function type check
271 | */
272 | exports.isFunc = function (v) { return typeof v === 'function'; };
273 | /**
274 | * Quick object check - this is primarily used to tell
275 | * Objects from primitive values when we know the value
276 | * is a JSON-compliant type.
277 | */
278 | exports.isObj = exports.isObject = function (obj) {
279 | return obj !== null && typeof obj === 'object'
280 | };
281 |
282 | /**
283 | * Strict object type check. Only returns true
284 | * for plain JavaScript objects.
285 | */
286 | var _toString = Object.prototype.toString;
287 | exports.isPlainObject = function (obj) {
288 | return _toString.call(obj) === '[object Object]'
289 | };
290 |
291 | /**
292 | * Check whether the object has the property.
293 | */
294 | var hasOwnProperty = Object.prototype.hasOwnProperty;
295 | exports.hasOwn = function (obj, key) {
296 | return hasOwnProperty.call(obj, key)
297 | };
298 |
299 | /**
300 | * Perform no operation.
301 | * Stubbing args to make Flow happy without leaving useless transpiled code
302 | * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/)
303 | */
304 | exports.noop = function (a, b, c) {};
305 |
306 | /**
307 | * Check if val is a valid array index.
308 | */
309 | exports.isValidArrayIndex = function (val) {
310 | var n = parseFloat(String(val));
311 | return n >= 0 && Math.floor(n) === n && isFinite(val)
312 | };
313 | });
314 |
315 | var tools_7 = tools.isFunc;
316 | var tools_10 = tools.isPlainObject;
317 |
318 | var EVENT_TYPE = ['ready', 'beforeImageLoad', 'beforeDraw', 'imageLoad'];
319 |
320 | function observer () {
321 | var self = this;
322 |
323 | self.on = function (event, fn) {
324 | if (EVENT_TYPE.indexOf(event) > -1) {
325 | if (tools_7(fn)) {
326 | event === 'ready'
327 | ? fn(self)
328 | : self[("on" + (firstLetterUpper(event)))] = fn;
329 | }
330 | } else {
331 | console.error(("event: " + event + " is invalid"));
332 | }
333 | return self
334 | };
335 | }
336 |
337 | function wxPromise (fn) {
338 | return function (obj) {
339 | var args = [], len = arguments.length - 1;
340 | while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
341 |
342 | if ( obj === void 0 ) obj = {};
343 | return new Promise(function (resolve, reject) {
344 | obj.success = function (res) {
345 | resolve(res);
346 | };
347 | obj.fail = function (err) {
348 | reject(err);
349 | };
350 | fn.apply(void 0, [ obj ].concat( args ));
351 | })
352 | }
353 | }
354 |
355 | function draw (ctx, reserve) {
356 | if ( reserve === void 0 ) reserve = false;
357 |
358 | return new Promise(function (resolve) {
359 | ctx.draw(reserve, resolve);
360 | })
361 | }
362 |
363 | var getImageInfo = wxPromise(wx.getImageInfo);
364 |
365 | var canvasToTempFilePath = wxPromise(wx.canvasToTempFilePath);
366 |
367 | var base64 = createCommonjsModule(function (module, exports) {
368 | /*! http://mths.be/base64 v0.1.0 by @mathias | MIT license */
369 | (function(root) {
370 |
371 | // Detect free variables `exports`.
372 | var freeExports = 'object' == 'object' && exports;
373 |
374 | // Detect free variable `module`.
375 | var freeModule = 'object' == 'object' && module &&
376 | module.exports == freeExports && module;
377 |
378 | // Detect free variable `global`, from Node.js or Browserified code, and use
379 | // it as `root`.
380 | var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal;
381 | if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
382 | root = freeGlobal;
383 | }
384 |
385 | /*--------------------------------------------------------------------------*/
386 |
387 | var InvalidCharacterError = function(message) {
388 | this.message = message;
389 | };
390 | InvalidCharacterError.prototype = new Error;
391 | InvalidCharacterError.prototype.name = 'InvalidCharacterError';
392 |
393 | var error = function(message) {
394 | // Note: the error messages used throughout this file match those used by
395 | // the native `atob`/`btoa` implementation in Chromium.
396 | throw new InvalidCharacterError(message);
397 | };
398 |
399 | var TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
400 | // http://whatwg.org/html/common-microsyntaxes.html#space-character
401 | var REGEX_SPACE_CHARACTERS = /[\t\n\f\r ]/g;
402 |
403 | // `decode` is designed to be fully compatible with `atob` as described in the
404 | // HTML Standard. http://whatwg.org/html/webappapis.html#dom-windowbase64-atob
405 | // The optimized base64-decoding algorithm used is based on @atk’s excellent
406 | // implementation. https://gist.github.com/atk/1020396
407 | var decode = function(input) {
408 | input = String(input)
409 | .replace(REGEX_SPACE_CHARACTERS, '');
410 | var length = input.length;
411 | if (length % 4 == 0) {
412 | input = input.replace(/==?$/, '');
413 | length = input.length;
414 | }
415 | if (
416 | length % 4 == 1 ||
417 | // http://whatwg.org/C#alphanumeric-ascii-characters
418 | /[^+a-zA-Z0-9/]/.test(input)
419 | ) {
420 | error(
421 | 'Invalid character: the string to be decoded is not correctly encoded.'
422 | );
423 | }
424 | var bitCounter = 0;
425 | var bitStorage;
426 | var buffer;
427 | var output = '';
428 | var position = -1;
429 | while (++position < length) {
430 | buffer = TABLE.indexOf(input.charAt(position));
431 | bitStorage = bitCounter % 4 ? bitStorage * 64 + buffer : buffer;
432 | // Unless this is the first of a group of 4 characters…
433 | if (bitCounter++ % 4) {
434 | // …convert the first 8 bits to a single ASCII character.
435 | output += String.fromCharCode(
436 | 0xFF & bitStorage >> (-2 * bitCounter & 6)
437 | );
438 | }
439 | }
440 | return output;
441 | };
442 |
443 | // `encode` is designed to be fully compatible with `btoa` as described in the
444 | // HTML Standard: http://whatwg.org/html/webappapis.html#dom-windowbase64-btoa
445 | var encode = function(input) {
446 | input = String(input);
447 | if (/[^\0-\xFF]/.test(input)) {
448 | // Note: no need to special-case astral symbols here, as surrogates are
449 | // matched, and the input is supposed to only contain ASCII anyway.
450 | error(
451 | 'The string to be encoded contains characters outside of the ' +
452 | 'Latin1 range.'
453 | );
454 | }
455 | var padding = input.length % 3;
456 | var output = '';
457 | var position = -1;
458 | var a;
459 | var b;
460 | var c;
461 | var buffer;
462 | // Make sure any padding is handled outside of the loop.
463 | var length = input.length - padding;
464 |
465 | while (++position < length) {
466 | // Read three bytes, i.e. 24 bits.
467 | a = input.charCodeAt(position) << 16;
468 | b = input.charCodeAt(++position) << 8;
469 | c = input.charCodeAt(++position);
470 | buffer = a + b + c;
471 | // Turn the 24 bits into four chunks of 6 bits each, and append the
472 | // matching character for each of them to the output.
473 | output += (
474 | TABLE.charAt(buffer >> 18 & 0x3F) +
475 | TABLE.charAt(buffer >> 12 & 0x3F) +
476 | TABLE.charAt(buffer >> 6 & 0x3F) +
477 | TABLE.charAt(buffer & 0x3F)
478 | );
479 | }
480 |
481 | if (padding == 2) {
482 | a = input.charCodeAt(position) << 8;
483 | b = input.charCodeAt(++position);
484 | buffer = a + b;
485 | output += (
486 | TABLE.charAt(buffer >> 10) +
487 | TABLE.charAt((buffer >> 4) & 0x3F) +
488 | TABLE.charAt((buffer << 2) & 0x3F) +
489 | '='
490 | );
491 | } else if (padding == 1) {
492 | buffer = input.charCodeAt(position);
493 | output += (
494 | TABLE.charAt(buffer >> 2) +
495 | TABLE.charAt((buffer << 4) & 0x3F) +
496 | '=='
497 | );
498 | }
499 |
500 | return output;
501 | };
502 |
503 | var base64 = {
504 | 'encode': encode,
505 | 'decode': decode,
506 | 'version': '0.1.0'
507 | };
508 |
509 | // Some AMD build optimizers, like r.js, check for specific condition patterns
510 | // like the following:
511 | if (
512 | typeof undefined == 'function' &&
513 | typeof undefined.amd == 'object' &&
514 | undefined.amd
515 | ) {
516 | undefined(function() {
517 | return base64;
518 | });
519 | } else if (freeExports && !freeExports.nodeType) {
520 | if (freeModule) { // in Node.js or RingoJS v0.8.0+
521 | freeModule.exports = base64;
522 | } else { // in Narwhal or RingoJS v0.7.0-
523 | for (var key in base64) {
524 | base64.hasOwnProperty(key) && (freeExports[key] = base64[key]);
525 | }
526 | }
527 | } else { // in Rhino or a web browser
528 | root.base64 = base64;
529 | }
530 |
531 | }(commonjsGlobal));
532 | });
533 |
534 | function makeURI (strData, type) {
535 | return 'data:' + type + ';base64,' + strData
536 | }
537 |
538 | function fixType (type) {
539 | type = type.toLowerCase().replace(/jpg/i, 'jpeg');
540 | var r = type.match(/png|jpeg|bmp|gif/)[0];
541 | return 'image/' + r
542 | }
543 |
544 | function encodeData (data) {
545 | var str = '';
546 | if (typeof data === 'string') {
547 | str = data;
548 | } else {
549 | for (var i = 0; i < data.length; i++) {
550 | str += String.fromCharCode(data[i]);
551 | }
552 | }
553 | return base64.encode(str)
554 | }
555 |
556 | /**
557 | * 获取图像区域隐含的像素数据
558 | * @param canvasId canvas标识
559 | * @param x 将要被提取的图像数据矩形区域的左上角 x 坐标
560 | * @param y 将要被提取的图像数据矩形区域的左上角 y 坐标
561 | * @param width 将要被提取的图像数据矩形区域的宽度
562 | * @param height 将要被提取的图像数据矩形区域的高度
563 | * @param done 完成回调
564 | */
565 | function getImageData (canvasId, x, y, width, height, done) {
566 | wx.canvasGetImageData({
567 | canvasId: canvasId,
568 | x: x,
569 | y: y,
570 | width: width,
571 | height: height,
572 | success: function success (res) {
573 | done(res, null);
574 | },
575 | fail: function fail (res) {
576 | done(null, res);
577 | }
578 | });
579 | }
580 |
581 | /**
582 | * 生成bmp格式图片
583 | * 按照规则生成图片响应头和响应体
584 | * @param oData 用来描述 canvas 区域隐含的像素数据 { data, width, height } = oData
585 | * @returns {*} base64字符串
586 | */
587 | function genBitmapImage (oData) {
588 | //
589 | // BITMAPFILEHEADER: http://msdn.microsoft.com/en-us/library/windows/desktop/dd183374(v=vs.85).aspx
590 | // BITMAPINFOHEADER: http://msdn.microsoft.com/en-us/library/dd183376.aspx
591 | //
592 | var biWidth = oData.width;
593 | var biHeight = oData.height;
594 | var biSizeImage = biWidth * biHeight * 3;
595 | var bfSize = biSizeImage + 54; // total header size = 54 bytes
596 |
597 | //
598 | // typedef struct tagBITMAPFILEHEADER {
599 | // WORD bfType;
600 | // DWORD bfSize;
601 | // WORD bfReserved1;
602 | // WORD bfReserved2;
603 | // DWORD bfOffBits;
604 | // } BITMAPFILEHEADER;
605 | //
606 | var BITMAPFILEHEADER = [
607 | // WORD bfType -- The file type signature; must be "BM"
608 | 0x42, 0x4D,
609 | // DWORD bfSize -- The size, in bytes, of the bitmap file
610 | bfSize & 0xff, bfSize >> 8 & 0xff, bfSize >> 16 & 0xff, bfSize >> 24 & 0xff,
611 | // WORD bfReserved1 -- Reserved; must be zero
612 | 0, 0,
613 | // WORD bfReserved2 -- Reserved; must be zero
614 | 0, 0,
615 | // DWORD bfOffBits -- The offset, in bytes, from the beginning of the BITMAPFILEHEADER structure to the bitmap bits.
616 | 54, 0, 0, 0
617 | ];
618 |
619 | //
620 | // typedef struct tagBITMAPINFOHEADER {
621 | // DWORD biSize;
622 | // LONG biWidth;
623 | // LONG biHeight;
624 | // WORD biPlanes;
625 | // WORD biBitCount;
626 | // DWORD biCompression;
627 | // DWORD biSizeImage;
628 | // LONG biXPelsPerMeter;
629 | // LONG biYPelsPerMeter;
630 | // DWORD biClrUsed;
631 | // DWORD biClrImportant;
632 | // } BITMAPINFOHEADER, *PBITMAPINFOHEADER;
633 | //
634 | var BITMAPINFOHEADER = [
635 | // DWORD biSize -- The number of bytes required by the structure
636 | 40, 0, 0, 0,
637 | // LONG biWidth -- The width of the bitmap, in pixels
638 | biWidth & 0xff, biWidth >> 8 & 0xff, biWidth >> 16 & 0xff, biWidth >> 24 & 0xff,
639 | // LONG biHeight -- The height of the bitmap, in pixels
640 | biHeight & 0xff, biHeight >> 8 & 0xff, biHeight >> 16 & 0xff, biHeight >> 24 & 0xff,
641 | // WORD biPlanes -- The number of planes for the target device. This value must be set to 1
642 | 1, 0,
643 | // WORD biBitCount -- The number of bits-per-pixel, 24 bits-per-pixel -- the bitmap
644 | // has a maximum of 2^24 colors (16777216, Truecolor)
645 | 24, 0,
646 | // DWORD biCompression -- The type of compression, BI_RGB (code 0) -- uncompressed
647 | 0, 0, 0, 0,
648 | // DWORD biSizeImage -- The size, in bytes, of the image. This may be set to zero for BI_RGB bitmaps
649 | biSizeImage & 0xff, biSizeImage >> 8 & 0xff, biSizeImage >> 16 & 0xff, biSizeImage >> 24 & 0xff,
650 | // LONG biXPelsPerMeter, unused
651 | 0, 0, 0, 0,
652 | // LONG biYPelsPerMeter, unused
653 | 0, 0, 0, 0,
654 | // DWORD biClrUsed, the number of color indexes of palette, unused
655 | 0, 0, 0, 0,
656 | // DWORD biClrImportant, unused
657 | 0, 0, 0, 0
658 | ];
659 |
660 | var iPadding = (4 - ((biWidth * 3) % 4)) % 4;
661 |
662 | var aImgData = oData.data;
663 |
664 | var strPixelData = '';
665 | var biWidth4 = biWidth << 2;
666 | var y = biHeight;
667 | var fromCharCode = String.fromCharCode;
668 |
669 | do {
670 | var iOffsetY = biWidth4 * (y - 1);
671 | var strPixelRow = '';
672 | for (var x = 0; x < biWidth; x++) {
673 | var iOffsetX = x << 2;
674 | strPixelRow += fromCharCode(aImgData[iOffsetY + iOffsetX + 2]) +
675 | fromCharCode(aImgData[iOffsetY + iOffsetX + 1]) +
676 | fromCharCode(aImgData[iOffsetY + iOffsetX]);
677 | }
678 |
679 | for (var c = 0; c < iPadding; c++) {
680 | strPixelRow += String.fromCharCode(0);
681 | }
682 |
683 | strPixelData += strPixelRow;
684 | } while (--y)
685 |
686 | var strEncoded = encodeData(BITMAPFILEHEADER.concat(BITMAPINFOHEADER)) + encodeData(strPixelData);
687 |
688 | return strEncoded
689 | }
690 |
691 | /**
692 | * 转换为图片base64
693 | * @param canvasId canvas标识
694 | * @param x 将要被提取的图像数据矩形区域的左上角 x 坐标
695 | * @param y 将要被提取的图像数据矩形区域的左上角 y 坐标
696 | * @param width 将要被提取的图像数据矩形区域的宽度
697 | * @param height 将要被提取的图像数据矩形区域的高度
698 | * @param type 转换图片类型
699 | * @param done 完成回调
700 | */
701 | function convertToImage (canvasId, x, y, width, height, type, done) {
702 | if ( done === void 0 ) done = function () {};
703 |
704 | if (type === undefined) { type = 'png'; }
705 | type = fixType(type);
706 | if (/bmp/.test(type)) {
707 | getImageData(canvasId, x, y, width, height, function (data, err) {
708 | var strData = genBitmapImage(data);
709 | tools_7(done) && done(makeURI(strData, 'image/' + type), err);
710 | });
711 | } else {
712 | console.error('暂不支持生成\'' + type + '\'类型的base64图片');
713 | }
714 | }
715 |
716 | var CanvasToBase64 = {
717 | convertToImage: convertToImage,
718 | // convertToPNG: function (width, height, done) {
719 | // return convertToImage(width, height, 'png', done)
720 | // },
721 | // convertToJPEG: function (width, height, done) {
722 | // return convertToImage(width, height, 'jpeg', done)
723 | // },
724 | // convertToGIF: function (width, height, done) {
725 | // return convertToImage(width, height, 'gif', done)
726 | // },
727 | convertToBMP: function (ref, done) {
728 | if ( ref === void 0 ) ref = {};
729 | var canvasId = ref.canvasId;
730 | var x = ref.x;
731 | var y = ref.y;
732 | var width = ref.width;
733 | var height = ref.height;
734 | if ( done === void 0 ) done = function () {};
735 |
736 | return convertToImage(canvasId, x, y, width, height, 'bmp', done)
737 | }
738 | };
739 |
740 | function methods () {
741 | var self = this;
742 |
743 | var boundWidth = self.width; // 裁剪框默认宽度,即整个画布宽度
744 | var boundHeight = self.height; // 裁剪框默认高度,即整个画布高度
745 |
746 | var id = self.id;
747 | var targetId = self.targetId;
748 | var pixelRatio = self.pixelRatio;
749 |
750 | var ref = self.cut;
751 | var x = ref.x; if ( x === void 0 ) x = 0;
752 | var y = ref.y; if ( y === void 0 ) y = 0;
753 | var width = ref.width; if ( width === void 0 ) width = boundWidth;
754 | var height = ref.height; if ( height === void 0 ) height = boundHeight;
755 |
756 | self.updateCanvas = function (done) {
757 | if (self.croperTarget) {
758 | // 画布绘制图片
759 | self.ctx.drawImage(
760 | self.croperTarget,
761 | self.imgLeft,
762 | self.imgTop,
763 | self.scaleWidth,
764 | self.scaleHeight
765 | );
766 | }
767 | tools_7(self.onBeforeDraw) && self.onBeforeDraw(self.ctx, self);
768 |
769 | self.setBoundStyle(self.boundStyle); // 设置边界样式
770 |
771 | self.ctx.draw(false, done);
772 | return self
773 | };
774 |
775 | self.pushOrigin = self.pushOrign = function (src) {
776 | self.src = src;
777 |
778 | tools_7(self.onBeforeImageLoad) && self.onBeforeImageLoad(self.ctx, self);
779 |
780 | return getImageInfo({ src: src })
781 | .then(function (res) {
782 | var innerAspectRadio = res.width / res.height;
783 | var customAspectRadio = width / height;
784 |
785 | self.croperTarget = res.path;
786 |
787 | if (innerAspectRadio < customAspectRadio) {
788 | self.rectX = x;
789 | self.baseWidth = width;
790 | self.baseHeight = width / innerAspectRadio;
791 | self.rectY = y - Math.abs((height - self.baseHeight) / 2);
792 | } else {
793 | self.rectY = y;
794 | self.baseWidth = height * innerAspectRadio;
795 | self.baseHeight = height;
796 | self.rectX = x - Math.abs((width - self.baseWidth) / 2);
797 | }
798 |
799 | self.imgLeft = self.rectX;
800 | self.imgTop = self.rectY;
801 | self.scaleWidth = self.baseWidth;
802 | self.scaleHeight = self.baseHeight;
803 |
804 | self.update();
805 |
806 | return new Promise(function (resolve) {
807 | self.updateCanvas(resolve);
808 | })
809 | })
810 | .then(function () {
811 | tools_7(self.onImageLoad) && self.onImageLoad(self.ctx, self);
812 | })
813 | };
814 |
815 | self.removeImage = function () {
816 | self.src = '';
817 | self.croperTarget = '';
818 | return draw(self.ctx)
819 | };
820 |
821 | self.getCropperBase64 = function (done) {
822 | if ( done === void 0 ) done = function () {};
823 |
824 | CanvasToBase64.convertToBMP({
825 | canvasId: id,
826 | x: x,
827 | y: y,
828 | width: width,
829 | height: height
830 | }, done);
831 | };
832 |
833 | self.getCropperImage = function (opt, fn) {
834 | var customOptions = opt;
835 |
836 | var canvasOptions = {
837 | canvasId: id,
838 | x: x,
839 | y: y,
840 | width: width,
841 | height: height
842 | };
843 |
844 | var task = function () { return Promise.resolve(); };
845 |
846 | if (
847 | tools_10(customOptions) &&
848 | customOptions.original
849 | ) {
850 | // original mode
851 | task = function () {
852 | self.targetCtx.drawImage(
853 | self.croperTarget,
854 | self.imgLeft * pixelRatio,
855 | self.imgTop * pixelRatio,
856 | self.scaleWidth * pixelRatio,
857 | self.scaleHeight * pixelRatio
858 | );
859 |
860 | canvasOptions = {
861 | canvasId: targetId,
862 | x: x * pixelRatio,
863 | y: y * pixelRatio,
864 | width: width * pixelRatio,
865 | height: height * pixelRatio
866 | };
867 |
868 | return draw(self.targetCtx)
869 | };
870 | }
871 |
872 | return task()
873 | .then(function () {
874 | if (tools_10(customOptions)) {
875 | canvasOptions = Object.assign({}, canvasOptions, customOptions);
876 | }
877 |
878 | if (tools_7(customOptions)) {
879 | fn = customOptions;
880 | }
881 |
882 | var arg = canvasOptions.componentContext
883 | ? [canvasOptions, canvasOptions.componentContext]
884 | : [canvasOptions];
885 |
886 | return canvasToTempFilePath.apply(null, arg)
887 | })
888 | .then(function (res) {
889 | var tempFilePath = res.tempFilePath;
890 |
891 | return tools_7(fn)
892 | ? fn.call(self, tempFilePath, null)
893 | : tempFilePath
894 | })
895 | .catch(function (err) {
896 | if (tools_7(fn)) {
897 | fn.call(self, null, err);
898 | } else {
899 | throw err
900 | }
901 | })
902 | };
903 | }
904 |
905 | /**
906 | * 获取最新缩放值
907 | * @param oldScale 上一次触摸结束后的缩放值
908 | * @param oldDistance 上一次触摸结束后的双指距离
909 | * @param zoom 缩放系数
910 | * @param touch0 第一指touch对象
911 | * @param touch1 第二指touch对象
912 | * @returns {*}
913 | */
914 | var getNewScale = function (oldScale, oldDistance, zoom, touch0, touch1) {
915 | var xMove, yMove, newDistance;
916 | // 计算二指最新距离
917 | xMove = Math.round(touch1.x - touch0.x);
918 | yMove = Math.round(touch1.y - touch0.y);
919 | newDistance = Math.round(Math.sqrt(xMove * xMove + yMove * yMove));
920 |
921 | return oldScale + 0.001 * zoom * (newDistance - oldDistance)
922 | };
923 |
924 | function update () {
925 | var self = this;
926 |
927 | if (!self.src) { return }
928 |
929 | self.__oneTouchStart = function (touch) {
930 | self.touchX0 = Math.round(touch.x);
931 | self.touchY0 = Math.round(touch.y);
932 | };
933 |
934 | self.__oneTouchMove = function (touch) {
935 | var xMove, yMove;
936 | // 计算单指移动的距离
937 | if (self.touchended) {
938 | return self.updateCanvas()
939 | }
940 | xMove = Math.round(touch.x - self.touchX0);
941 | yMove = Math.round(touch.y - self.touchY0);
942 |
943 | var imgLeft = Math.round(self.rectX + xMove);
944 | var imgTop = Math.round(self.rectY + yMove);
945 |
946 | self.outsideBound(imgLeft, imgTop);
947 |
948 | self.updateCanvas();
949 | };
950 |
951 | self.__twoTouchStart = function (touch0, touch1) {
952 | var xMove, yMove, oldDistance;
953 |
954 | self.touchX1 = Math.round(self.rectX + self.scaleWidth / 2);
955 | self.touchY1 = Math.round(self.rectY + self.scaleHeight / 2);
956 |
957 | // 计算两指距离
958 | xMove = Math.round(touch1.x - touch0.x);
959 | yMove = Math.round(touch1.y - touch0.y);
960 | oldDistance = Math.round(Math.sqrt(xMove * xMove + yMove * yMove));
961 |
962 | self.oldDistance = oldDistance;
963 | };
964 |
965 | self.__twoTouchMove = function (touch0, touch1) {
966 | var oldScale = self.oldScale;
967 | var oldDistance = self.oldDistance;
968 | var scale = self.scale;
969 | var zoom = self.zoom;
970 |
971 | self.newScale = getNewScale(oldScale, oldDistance, zoom, touch0, touch1);
972 |
973 | // 设定缩放范围
974 | self.newScale <= 1 && (self.newScale = 1);
975 | self.newScale >= scale && (self.newScale = scale);
976 |
977 | self.scaleWidth = Math.round(self.newScale * self.baseWidth);
978 | self.scaleHeight = Math.round(self.newScale * self.baseHeight);
979 | var imgLeft = Math.round(self.touchX1 - self.scaleWidth / 2);
980 | var imgTop = Math.round(self.touchY1 - self.scaleHeight / 2);
981 |
982 | self.outsideBound(imgLeft, imgTop);
983 |
984 | self.updateCanvas();
985 | };
986 |
987 | self.__xtouchEnd = function () {
988 | self.oldScale = self.newScale;
989 | self.rectX = self.imgLeft;
990 | self.rectY = self.imgTop;
991 | };
992 | }
993 |
994 | var handle = {
995 | // 图片手势初始监测
996 | touchStart: function touchStart (e) {
997 | var self = this;
998 | var ref = e.touches;
999 | var touch0 = ref[0];
1000 | var touch1 = ref[1];
1001 |
1002 | if (!self.src) { return }
1003 |
1004 | setTouchState(self, true, null, null);
1005 |
1006 | // 计算第一个触摸点的位置,并参照改点进行缩放
1007 | self.__oneTouchStart(touch0);
1008 |
1009 | // 两指手势触发
1010 | if (e.touches.length >= 2) {
1011 | self.__twoTouchStart(touch0, touch1);
1012 | }
1013 | },
1014 |
1015 | // 图片手势动态缩放
1016 | touchMove: function touchMove (e) {
1017 | var self = this;
1018 | var ref = e.touches;
1019 | var touch0 = ref[0];
1020 | var touch1 = ref[1];
1021 |
1022 | if (!self.src) { return }
1023 |
1024 | setTouchState(self, null, true);
1025 |
1026 | // 单指手势时触发
1027 | if (e.touches.length === 1) {
1028 | self.__oneTouchMove(touch0);
1029 | }
1030 | // 两指手势触发
1031 | if (e.touches.length >= 2) {
1032 | self.__twoTouchMove(touch0, touch1);
1033 | }
1034 | },
1035 |
1036 | touchEnd: function touchEnd (e) {
1037 | var self = this;
1038 |
1039 | if (!self.src) { return }
1040 |
1041 | setTouchState(self, false, false, true);
1042 | self.__xtouchEnd();
1043 | }
1044 | };
1045 |
1046 | function cut () {
1047 | var self = this;
1048 | var boundWidth = self.width; // 裁剪框默认宽度,即整个画布宽度
1049 | var boundHeight = self.height;
1050 | // 裁剪框默认高度,即整个画布高度
1051 | var ref = self.cut;
1052 | var x = ref.x; if ( x === void 0 ) x = 0;
1053 | var y = ref.y; if ( y === void 0 ) y = 0;
1054 | var width = ref.width; if ( width === void 0 ) width = boundWidth;
1055 | var height = ref.height; if ( height === void 0 ) height = boundHeight;
1056 |
1057 | /**
1058 | * 设置边界
1059 | * @param imgLeft 图片左上角横坐标值
1060 | * @param imgTop 图片左上角纵坐标值
1061 | */
1062 | self.outsideBound = function (imgLeft, imgTop) {
1063 | self.imgLeft = imgLeft >= x
1064 | ? x
1065 | : self.scaleWidth + imgLeft - x <= width
1066 | ? x + width - self.scaleWidth
1067 | : imgLeft;
1068 |
1069 | self.imgTop = imgTop >= y
1070 | ? y
1071 | : self.scaleHeight + imgTop - y <= height
1072 | ? y + height - self.scaleHeight
1073 | : imgTop;
1074 | };
1075 |
1076 | /**
1077 | * 设置边界样式
1078 | * @param color 边界颜色
1079 | */
1080 | self.setBoundStyle = function (ref) {
1081 | if ( ref === void 0 ) ref = {};
1082 | var color = ref.color; if ( color === void 0 ) color = '#04b00f';
1083 | var mask = ref.mask; if ( mask === void 0 ) mask = 'rgba(0, 0, 0, 0.3)';
1084 | var lineWidth = ref.lineWidth; if ( lineWidth === void 0 ) lineWidth = 1;
1085 |
1086 | var half = lineWidth / 2;
1087 | var boundOption = [
1088 | {
1089 | start: { x: x - half, y: y + 10 - half },
1090 | step1: { x: x - half, y: y - half },
1091 | step2: { x: x + 10 - half, y: y - half }
1092 | },
1093 | {
1094 | start: { x: x - half, y: y + height - 10 + half },
1095 | step1: { x: x - half, y: y + height + half },
1096 | step2: { x: x + 10 - half, y: y + height + half }
1097 | },
1098 | {
1099 | start: { x: x + width - 10 + half, y: y - half },
1100 | step1: { x: x + width + half, y: y - half },
1101 | step2: { x: x + width + half, y: y + 10 - half }
1102 | },
1103 | {
1104 | start: { x: x + width + half, y: y + height - 10 + half },
1105 | step1: { x: x + width + half, y: y + height + half },
1106 | step2: { x: x + width - 10 + half, y: y + height + half }
1107 | }
1108 | ];
1109 |
1110 | // 绘制半透明层
1111 | self.ctx.beginPath();
1112 | self.ctx.setFillStyle(mask);
1113 | self.ctx.fillRect(0, 0, x, boundHeight);
1114 | self.ctx.fillRect(x, 0, width, y);
1115 | self.ctx.fillRect(x, y + height, width, boundHeight - y - height);
1116 | self.ctx.fillRect(x + width, 0, boundWidth - x - width, boundHeight);
1117 | self.ctx.fill();
1118 |
1119 | boundOption.forEach(function (op) {
1120 | self.ctx.beginPath();
1121 | self.ctx.setStrokeStyle(color);
1122 | self.ctx.setLineWidth(lineWidth);
1123 | self.ctx.moveTo(op.start.x, op.start.y);
1124 | self.ctx.lineTo(op.step1.x, op.step1.y);
1125 | self.ctx.lineTo(op.step2.x, op.step2.y);
1126 | self.ctx.stroke();
1127 | });
1128 | };
1129 | }
1130 |
1131 | var version = "1.3.9";
1132 |
1133 | var WeCropper = function WeCropper (params) {
1134 | var self = this;
1135 | var _default = {};
1136 |
1137 | validator(self, DEFAULT);
1138 |
1139 | Object.keys(DEFAULT).forEach(function (key) {
1140 | _default[key] = DEFAULT[key].default;
1141 | });
1142 | Object.assign(self, _default, params);
1143 |
1144 | self.prepare();
1145 | self.attachPage();
1146 | self.createCtx();
1147 | self.observer();
1148 | self.cutt();
1149 | self.methods();
1150 | self.init();
1151 | self.update();
1152 |
1153 | return self
1154 | };
1155 |
1156 | WeCropper.prototype.init = function init () {
1157 | var self = this;
1158 | var src = self.src;
1159 |
1160 | self.version = version;
1161 |
1162 | typeof self.onReady === 'function' && self.onReady(self.ctx, self);
1163 |
1164 | if (src) {
1165 | self.pushOrign(src);
1166 | } else {
1167 | self.updateCanvas();
1168 | }
1169 | setTouchState(self, false, false, false);
1170 |
1171 | self.oldScale = 1;
1172 | self.newScale = 1;
1173 |
1174 | return self
1175 | };
1176 |
1177 | Object.assign(WeCropper.prototype, handle);
1178 |
1179 | WeCropper.prototype.prepare = prepare;
1180 | WeCropper.prototype.observer = observer;
1181 | WeCropper.prototype.methods = methods;
1182 | WeCropper.prototype.cutt = cut;
1183 | WeCropper.prototype.update = update;
1184 |
1185 | return WeCropper;
1186 |
1187 | })));
1188 |
--------------------------------------------------------------------------------