Commit 4a64798f authored by xiaochenghua's avatar xiaochenghua

feat: 提交代码

parents
File added
// app.js
App({
onLaunch() {
},
})
{
"pages":[
"pages/index/index"
],
"window":{
"backgroundTextStyle":"light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "快捷计算",
"navigationBarTextStyle":"black"
},
"style": "v2",
"sitemapLocation": "sitemap.json"
}
/**app.wxss**/
.container {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
padding: 200rpx 0;
box-sizing: border-box;
}
import WxCanvas from './wx-canvas';
import * as echarts from './echarts';
let ctx;
function compareVersion(v1, v2) {
v1 = v1.split('.')
v2 = v2.split('.')
const len = Math.max(v1.length, v2.length)
while (v1.length < len) {
v1.push('0')
}
while (v2.length < len) {
v2.push('0')
}
for (let i = 0; i < len; i++) {
const num1 = parseInt(v1[i])
const num2 = parseInt(v2[i])
if (num1 > num2) {
return 1
} else if (num1 < num2) {
return -1
}
}
return 0
}
Component({
properties: {
canvasId: {
type: String,
value: 'ec-canvas'
},
ec: {
type: Object
},
forceUseOldCanvas: {
type: Boolean,
value: false
}
},
data: {
isUseNewCanvas: false
},
ready: function () {
// Disable prograssive because drawImage doesn't support DOM as parameter
// See https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.drawImage.html
echarts.registerPreprocessor(option => {
if (option && option.series) {
if (option.series.length > 0) {
option.series.forEach(series => {
series.progressive = 0;
});
}
else if (typeof option.series === 'object') {
option.series.progressive = 0;
}
}
});
if (!this.data.ec) {
console.warn('组件需绑定 ec 变量,例:<ec-canvas id="mychart-dom-bar" '
+ 'canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>');
return;
}
if (!this.data.ec.lazyLoad) {
this.init();
}
},
methods: {
init: function (callback) {
const version = wx.getSystemInfoSync().SDKVersion
const canUseNewCanvas = compareVersion(version, '2.9.0') >= 0;
const forceUseOldCanvas = this.data.forceUseOldCanvas;
const isUseNewCanvas = canUseNewCanvas && !forceUseOldCanvas;
this.setData({ isUseNewCanvas });
if (forceUseOldCanvas && canUseNewCanvas) {
console.warn('开发者强制使用旧canvas,建议关闭');
}
if (isUseNewCanvas) {
// console.log('微信基础库版本大于2.9.0,开始使用<canvas type="2d"/>');
// 2.9.0 可以使用 <canvas type="2d"></canvas>
this.initByNewWay(callback);
} else {
const isValid = compareVersion(version, '1.9.91') >= 0
if (!isValid) {
console.error('微信基础库版本过低,需大于等于 1.9.91。'
+ '参见:https://github.com/ecomfe/echarts-for-weixin'
+ '#%E5%BE%AE%E4%BF%A1%E7%89%88%E6%9C%AC%E8%A6%81%E6%B1%82');
return;
} else {
console.warn('建议将微信基础库调整大于等于2.9.0版本。升级后绘图将有更好性能');
this.initByOldWay(callback);
}
}
},
initByOldWay(callback) {
// 1.9.91 <= version < 2.9.0:原来的方式初始化
ctx = wx.createCanvasContext(this.data.canvasId, this);
const canvas = new WxCanvas(ctx, this.data.canvasId, false);
echarts.setCanvasCreator(() => {
return canvas;
});
// const canvasDpr = wx.getSystemInfoSync().pixelRatio // 微信旧的canvas不能传入dpr
const canvasDpr = 1
var query = wx.createSelectorQuery().in(this);
query.select('.ec-canvas').boundingClientRect(res => {
if (typeof callback === 'function') {
this.chart = callback(canvas, res.width, res.height, canvasDpr);
}
else if (this.data.ec && typeof this.data.ec.onInit === 'function') {
this.chart = this.data.ec.onInit(canvas, res.width, res.height, canvasDpr);
}
else {
this.triggerEvent('init', {
canvas: canvas,
width: res.width,
height: res.height,
canvasDpr: canvasDpr // 增加了dpr,可方便外面echarts.init
});
}
}).exec();
},
initByNewWay(callback) {
// version >= 2.9.0:使用新的方式初始化
const query = wx.createSelectorQuery().in(this)
query
.select('.ec-canvas')
.fields({ node: true, size: true })
.exec(res => {
const canvasNode = res[0].node
this.canvasNode = canvasNode
const canvasDpr = wx.getSystemInfoSync().pixelRatio
const canvasWidth = res[0].width
const canvasHeight = res[0].height
const ctx = canvasNode.getContext('2d')
const canvas = new WxCanvas(ctx, this.data.canvasId, true, canvasNode)
echarts.setCanvasCreator(() => {
return canvas
})
if (typeof callback === 'function') {
this.chart = callback(canvas, canvasWidth, canvasHeight, canvasDpr)
} else if (this.data.ec && typeof this.data.ec.onInit === 'function') {
this.chart = this.data.ec.onInit(canvas, canvasWidth, canvasHeight, canvasDpr)
} else {
this.triggerEvent('init', {
canvas: canvas,
width: canvasWidth,
height: canvasHeight,
dpr: canvasDpr
})
}
})
},
canvasToTempFilePath(opt) {
if (this.data.isUseNewCanvas) {
// 新版
const query = wx.createSelectorQuery().in(this)
query
.select('.ec-canvas')
.fields({ node: true, size: true })
.exec(res => {
const canvasNode = res[0].node
opt.canvas = canvasNode
wx.canvasToTempFilePath(opt)
})
} else {
// 旧的
if (!opt.canvasId) {
opt.canvasId = this.data.canvasId;
}
ctx.draw(true, () => {
wx.canvasToTempFilePath(opt, this);
});
}
},
touchStart(e) {
if (this.chart && e.touches.length > 0) {
var touch = e.touches[0];
var handler = this.chart.getZr().handler;
handler.dispatch('mousedown', {
zrX: touch.x,
zrY: touch.y
});
handler.dispatch('mousemove', {
zrX: touch.x,
zrY: touch.y
});
handler.processGesture(wrapTouch(e), 'start');
}
},
touchMove(e) {
if (this.chart && e.touches.length > 0) {
var touch = e.touches[0];
var handler = this.chart.getZr().handler;
handler.dispatch('mousemove', {
zrX: touch.x,
zrY: touch.y
});
handler.processGesture(wrapTouch(e), 'change');
}
},
touchEnd(e) {
if (this.chart) {
const touch = e.changedTouches ? e.changedTouches[0] : {};
var handler = this.chart.getZr().handler;
handler.dispatch('mouseup', {
zrX: touch.x,
zrY: touch.y
});
handler.dispatch('click', {
zrX: touch.x,
zrY: touch.y
});
handler.processGesture(wrapTouch(e), 'end');
}
}
}
});
function wrapTouch(event) {
for (let i = 0; i < event.touches.length; ++i) {
const touch = event.touches[i];
touch.offsetX = touch.x;
touch.offsetY = touch.y;
}
return event;
}
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file
<!-- 新的:接口对其了H5 -->
<canvas wx:if="{{isUseNewCanvas}}" type="2d" class="ec-canvas" canvas-id="{{ canvasId }}" bindinit="init" bindtouchstart="{{ ec.disableTouch ? '' : 'touchStart' }}" bindtouchmove="{{ ec.disableTouch ? '' : 'touchMove' }}" bindtouchend="{{ ec.disableTouch ? '' : 'touchEnd' }}"></canvas>
<!-- 旧的 -->
<canvas wx:else class="ec-canvas" canvas-id="{{ canvasId }}" bindinit="init" bindtouchstart="{{ ec.disableTouch ? '' : 'touchStart' }}" bindtouchmove="{{ ec.disableTouch ? '' : 'touchMove' }}" bindtouchend="{{ ec.disableTouch ? '' : 'touchEnd' }}"></canvas>
.ec-canvas {
width: 100%;
height: 100%;
}
This source diff could not be displayed because it is too large. You can view the blob instead.
export default class WxCanvas {
constructor(ctx, canvasId, isNew, canvasNode) {
this.ctx = ctx;
this.canvasId = canvasId;
this.chart = null;
this.isNew = isNew
if (isNew) {
this.canvasNode = canvasNode;
}
else {
this._initStyle(ctx);
}
// this._initCanvas(zrender, ctx);
this._initEvent();
}
getContext(contextType) {
if (contextType === '2d') {
return this.ctx;
}
}
// canvasToTempFilePath(opt) {
// if (!opt.canvasId) {
// opt.canvasId = this.canvasId;
// }
// return wx.canvasToTempFilePath(opt, this);
// }
setChart(chart) {
this.chart = chart;
}
attachEvent() {
// noop
}
detachEvent() {
// noop
}
_initCanvas(zrender, ctx) {
zrender.util.getContext = function () {
return ctx;
};
zrender.util.$override('measureText', function (text, font) {
ctx.font = font || '12px sans-serif';
return ctx.measureText(text);
});
}
_initStyle(ctx) {
var styles = ['fillStyle', 'strokeStyle', 'globalAlpha',
'textAlign', 'textBaseAlign', 'shadow', 'lineWidth',
'lineCap', 'lineJoin', 'lineDash', 'miterLimit', 'fontSize'];
styles.forEach(style => {
Object.defineProperty(ctx, style, {
set: value => {
if (style !== 'fillStyle' && style !== 'strokeStyle'
|| value !== 'none' && value !== null
) {
ctx['set' + style.charAt(0).toUpperCase() + style.slice(1)](value);
}
}
});
});
ctx.createRadialGradient = () => {
return ctx.createCircularGradient(arguments);
};
}
_initEvent() {
this.event = {};
const eventNames = [{
wxName: 'touchStart',
ecName: 'mousedown'
}, {
wxName: 'touchMove',
ecName: 'mousemove'
}, {
wxName: 'touchEnd',
ecName: 'mouseup'
}, {
wxName: 'touchEnd',
ecName: 'click'
}];
eventNames.forEach(name => {
this.event[name.wxName] = e => {
const touch = e.touches[0];
this.chart.getZr().handler.dispatch(name.ecName, {
zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
zrY: name.wxName === 'tap' ? touch.clientY : touch.y
});
};
});
}
set width(w) {
if (this.canvasNode) this.canvasNode.width = w
}
set height(h) {
if (this.canvasNode) this.canvasNode.height = h
}
get width() {
if (this.canvasNode)
return this.canvasNode.width
return 0
}
get height() {
if (this.canvasNode)
return this.canvasNode.height
return 0
}
}
File added
import calendarFormatter from '../../utils/calendarFormatter';
import {formatTime} from '../../utils/util';
import * as echarts from '../../components/ec-canvas/echarts';
const G = ["","","","","","","","","",""]
const Z = ["","","","","","","","","","","",""]
const SGZ = [
Z.map((z, i) => `${G[i > 9 ? i - 9 : i]}${z}`),
Z.map((z, i) => `${G[i > 7 ? i - 8 : i + 2]}${z}`),
Z.map((z, i) => `${G[i > 5 ? i - 6 : i + 4]}${z}`),
Z.map((z, i) => `${G[i > 3 ? i - 4 : i + 6]}${z}`),
Z.map((z, i) => `${G[i > 1 ? i - 2 : i + 8]}${z}`),
];
const DATAH = [];
for (let i = 0; i< 24; i++) {
DATAH.push(i)
}
Page({
data: {
valueDate: formatTime(new Date()),
valueH: '0',
res: {},
dataH: DATAH,
wuxing: {
jin: 0,
mu: 0,
shui: 0,
huo: 0,
tu: 0,
},
ec: {
lazyLoad: true,
},
allColors: [
'rgb(130,57,53)',
'rgb(137,190,178)',
'rgb(201,186,131)',
'rgb(222,211,140)',
'rgb(222,156,83)',
'rgb(159,125,80)',
'rgb(17,63,61)',
'rgb(60,79,57)',
'rgb(98,92,51)',
'rgb(179,214,110)',
],
},
onLoad() {
this.echart =this.selectComponent('#mychart');
},
handleDate(e) {
this.setData({
valueDate: e.detail.value,
})
},
handleHour(e) {
this.setData({
valueH: e.detail.value,
})
},
handleScle() {
const { valueDate, valueH } = this.data;
const temp = valueDate.split('-');
const v = calendarFormatter.solar2lunar(temp[0],temp[1],temp[2]);
const d = v.gzDay[0];
const i = G.indexOf(d);
const r = i > 4 ? i - 5 : i;
const h = Math.floor((Number(valueH) + 1) / 2);
v.gzHour = SGZ[r][h > 0 && h < 12 ? h : 0];
const wuxing = this.getWuxing(v);
this.initChart(wuxing);
this.setData({
res: v,
wuxing,
});
},
getWuxing(v) {
const wuxing = [...`${v.gzYear}${v.gzMonth}${v.gzDay}${v.gzHour}${v.Animal}`];
const res = {
jin: 0,
mu: 0,
shui: 0,
huo: 0,
tu: 0,
};
wuxing.forEach(i => {
switch (true) {
case '庚辛申酉猴鸡'.indexOf(i) > -1:
res.jin += 1;
break;
case '甲乙寅卯虎兔'.indexOf(i) > -1:
res.mu += 1;
break;
case '壬癸亥子鼠猪'.indexOf(i) > -1:
res.shui += 1;
break;
case '丙丁巳午蛇马'.indexOf(i) > -1:
res.huo += 1;
break;
case '戊己辰戌丑未牛龙羊狗'.indexOf(i) > -1:
res.tu += 1;
break;
}
});
return res;
},
/**设置图表映射 */
initChart: function(wuxing) {
const option = {
series: [
{
name: 'Area Mode',
type: 'pie',
radius: [20, 140],
center: ['50%', '60%'],
roseType: 'area',
itemStyle: {
borderRadius: 5
},
data: [
{ value: wuxing.jin, name: '' },
{ value: wuxing.mu, name: '' },
{ value: wuxing.shui, name: '' },
{ value: wuxing.huo, name: '' },
{ value: wuxing.tu, name: '' },
]
}
]
};
//echarts会继承父元素的宽高,所以我们一定要设置echarts组件父元素的高度。
this.echart.init((canvas) => {
const chart = echarts.init(canvas, null, {
width: 400,
height: 400,
devicePixelRatio: 2,
});
//给echarts 设置数据及配置项(图表类型、数据量等)
chart.setOption(option);
console.log('=========')
return chart;
});
},
})
{
"usingComponents": {
"ec-canvas": "../../components/ec-canvas/ec-canvas"
}
}
\ No newline at end of file
<view class="page">
<view class="header">
<view class="title">生辰八字&五行</view>
</view>
<view class="center">
<view>
<picker mode="date" value="{{valueDate}}" bindchange="handleDate">
<view class="form-item">选择公历日期:{{valueDate}}</view>
</picker>
<picker bindchange="handleHour" value="{{valueH}}" range="{{dataH}}">
<view class="form-item">
时间:{{valueH}}点
</view>
</picker>
</view>
</view>
<button type="primary" class="button" bind:tap="handleScle">计算八字</button>
<view class="result">
<view class="nongli" wx:if="{{res.gzYear}}">
农历 {{res.gzYear}}{{res.Animal}}年 {{res.IMonthCn}} {{res.IDayCn}} {{res.ncWeek}}
</view>
<view class="flex-box" wx:if="{{res.gzYear}}">
<view class="res-title">八字:</view>
<view class="flex-content">
<view style="background-color: {{allColors[4]}};">{{res.gzYear}}</view>
<view style="background-color: {{allColors[1]}};">{{res.gzMonth}}</view>
<view style="background-color: {{allColors[2]}};">{{res.gzDay}}</view>
<view style="background-color: {{allColors[3]}};">{{res.gzHour}}</view>
</view>
</view>
<view class="flex-box" wx:if="{{res.gzYear}}">
<view class="res-title">五行:</view>
<view class="flex-content wx">
<view style="background-color: rgb(179, 63, 56);">金:{{wuxing.jin}}</view>
<view style="background-color: rgb(53,70,83);">木:{{wuxing.mu}}</view>
<view style="background-color: rgb(110,158,165);">水:{{wuxing.shui}}</view>
<view style="background-color: rgb(201,134,108);">火:{{wuxing.huo}}</view>
<view style="background-color: rgb(155,195,174);">土:{{wuxing.tu}}</view>
</view>
</view>
<view class="echart">
<ec-canvas id="mychart" canvas-id="mychart" ec="{{ ec }}"></ec-canvas>
</view>
</view>
</view>
\ No newline at end of file
.page {
/* padding: 32rpx; */
}
.header {
}
.title {
width: 100%;
text-align: center;
font-size: 48rpx;
margin: 32rpx 0;
}
.center {
margin: 32rpx;
}
.form-item {
height: 100rpx;
line-height: 100rpx;
border-bottom: 1px solid #e5e5e5;
}
.button {
width: 100%;
margin: 32rpx 0;
z-index: 8;
}
.result {
padding: 32rpx;
}
.echart {
height: 100vw;
margin-top: -120rpx;
}
.flex-box {
display: flex;
margin: 32rpx 0;
font-size: 36rpx;
}
.nongli, .res-title {
font-weight: 500;
font-size: 36rpx;
}
.flex-content {
flex: 1;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
font-size: 36rpx;
}
.flex-content view {
text-align: center;
width: 20%;
}
.wx {
flex-wrap: nowrap;
}
.wx view {
color: #fff;
margin-right: 3rpx;
}
{
"description": "项目配置文件",
"packOptions": {
"ignore": []
},
"setting": {
"bundle": false,
"userConfirmedBundleSwitch": false,
"urlCheck": true,
"scopeDataCheck": false,
"coverView": true,
"es6": true,
"postcss": true,
"compileHotReLoad": true,
"lazyloadPlaceholderEnable": false,
"preloadBackgroundData": false,
"minified": true,
"autoAudits": false,
"newFeature": false,
"uglifyFileName": false,
"uploadWithSourceMap": true,
"useIsolateContext": true,
"nodeModules": false,
"enhance": true,
"useMultiFrameRuntime": true,
"useApiHook": true,
"useApiHostProcess": true,
"showShadowRootInWxmlPanel": true,
"packNpmManually": false,
"enableEngineNative": false,
"packNpmRelationList": [],
"minifyWXSS": true,
"showES6CompileOption": false,
"minifyWXML": true
},
"compileType": "miniprogram",
"libVersion": "2.19.4",
"appid": "wxd04889271323534c",
"projectname": "wuxing",
"debugOptions": {
"hidedInDevtools": []
},
"scripts": {},
"staticServerOptions": {
"baseURL": "",
"servePath": ""
},
"isGameTourist": false,
"condition": {
"search": {
"list": []
},
"conversation": {
"list": []
},
"game": {
"list": []
},
"plugin": {
"list": []
},
"gamePlugin": {
"list": []
},
"miniprogram": {
"list": []
}
}
}
\ No newline at end of file
{
"desc": "关于本文件的更多信息,请参考文档 https://developers.weixin.qq.com/miniprogram/dev/framework/sitemap.html",
"rules": [{
"action": "allow",
"page": "*"
}]
}
\ No newline at end of file
This diff is collapsed.
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return `${[year, month, day].map(formatNumber).join('-')}`
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : `0${n}`
}
module.exports = {
formatTime
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment