MBTI人格测试 uniapp

index.vue 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. <template>
  2. <uni-shadow-root class="wxml-to-canvas-index"><canvas id="canvas" type="2d" :style="'width: '+(width)+'px; height: '+(height)+'px;'"></canvas></uni-shadow-root>
  3. </template>
  4. <script>
  5. global['__wxVueOptions'] = {components:{}}
  6. global['__wxRoute'] = 'wxml-to-canvas/index'
  7. (function webpackUniversalModuleDefinition(root, factory) {
  8. if(typeof exports === 'object' && typeof module === 'object')
  9. module.exports = factory();
  10. else if(typeof define === 'function' && define.amd)
  11. define([], factory);
  12. else {
  13. var a = factory();
  14. for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
  15. }
  16. })(window, function() {
  17. return /******/ (function(modules) { // webpackBootstrap
  18. /******/ // The module cache
  19. /******/ var installedModules = {};
  20. /******/
  21. /******/ // The require function
  22. /******/ function __webpack_require__(moduleId) {
  23. /******/
  24. /******/ // Check if module is in cache
  25. /******/ if(installedModules[moduleId]) {
  26. /******/ return installedModules[moduleId].exports;
  27. /******/ }
  28. /******/ // Create a new module (and put it into the cache)
  29. /******/ var module = installedModules[moduleId] = {
  30. /******/ i: moduleId,
  31. /******/ l: false,
  32. /******/ exports: {}
  33. /******/ };
  34. /******/
  35. /******/ // Execute the module function
  36. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  37. /******/
  38. /******/ // Flag the module as loaded
  39. /******/ module.l = true;
  40. /******/
  41. /******/ // Return the exports of the module
  42. /******/ return module.exports;
  43. /******/ }
  44. /******/
  45. /******/
  46. /******/ // expose the modules object (__webpack_modules__)
  47. /******/ __webpack_require__.m = modules;
  48. /******/
  49. /******/ // expose the module cache
  50. /******/ __webpack_require__.c = installedModules;
  51. /******/
  52. /******/ // define getter function for harmony exports
  53. /******/ __webpack_require__.d = function(exports, name, getter) {
  54. /******/ if(!__webpack_require__.o(exports, name)) {
  55. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  56. /******/ }
  57. /******/ };
  58. /******/
  59. /******/ // define __esModule on exports
  60. /******/ __webpack_require__.r = function(exports) {
  61. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  62. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  63. /******/ }
  64. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  65. /******/ };
  66. /******/
  67. /******/ // create a fake namespace object
  68. /******/ // mode & 1: value is a module id, require it
  69. /******/ // mode & 2: merge all properties of value into the ns
  70. /******/ // mode & 4: return value when already ns object
  71. /******/ // mode & 8|1: behave like require
  72. /******/ __webpack_require__.t = function(value, mode) {
  73. /******/ if(mode & 1) value = __webpack_require__(value);
  74. /******/ if(mode & 8) return value;
  75. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  76. /******/ var ns = Object.create(null);
  77. /******/ __webpack_require__.r(ns);
  78. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  79. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  80. /******/ return ns;
  81. /******/ };
  82. /******/
  83. /******/ // getDefaultExport function for compatibility with non-harmony modules
  84. /******/ __webpack_require__.n = function(module) {
  85. /******/ var getter = module && module.__esModule ?
  86. /******/ function getDefault() { return module['default']; } :
  87. /******/ function getModuleExports() { return module; };
  88. /******/ __webpack_require__.d(getter, 'a', getter);
  89. /******/ return getter;
  90. /******/ };
  91. /******/
  92. /******/ // Object.prototype.hasOwnProperty.call
  93. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  94. /******/
  95. /******/ // __webpack_public_path__
  96. /******/ __webpack_require__.p = "";
  97. /******/
  98. /******/
  99. /******/ // Load entry module and return exports
  100. /******/ return __webpack_require__(__webpack_require__.s = 0);
  101. /******/ })
  102. /************************************************************************/
  103. /******/ ([
  104. /* 0 */
  105. /***/ (function(module, exports, __webpack_require__) {
  106. const xmlParse = __webpack_require__(1)
  107. const {Widget} = __webpack_require__(2)
  108. const {Draw} = __webpack_require__(5)
  109. Component({
  110. properties: {
  111. width: {
  112. type: Number,
  113. value: 400
  114. },
  115. height: {
  116. type: Number,
  117. value: 300
  118. }
  119. },
  120. lifetimes: {
  121. attached() {
  122. const dpr = wx.getSystemInfoSync().pixelRatio
  123. const query = this.createSelectorQuery()
  124. this.dpr = dpr
  125. query.select('#canvas')
  126. .fields({node: true, size: true})
  127. .exec(res => {
  128. const canvas = res[0].node
  129. const ctx = canvas.getContext('2d')
  130. canvas.width = res[0].width * dpr
  131. canvas.height = res[0].height * dpr
  132. ctx.scale(dpr, dpr)
  133. this.ctx = ctx
  134. this.canvas = canvas
  135. })
  136. }
  137. },
  138. methods: {
  139. async renderToCanvas(args) {
  140. const {wxml, style} = args
  141. // 清空画布
  142. const ctx = this.ctx
  143. const canvas = this.canvas
  144. if (!ctx || !canvas) {
  145. return Promise.reject(new Error('renderToCanvas: fail canvas has not been created'))
  146. }
  147. ctx.clearRect(0, 0, this.data.width, this.data.height)
  148. const {root: xom} = xmlParse(wxml)
  149. const widget = new Widget(xom, style)
  150. const container = widget.init()
  151. this.boundary = {
  152. top: container.layoutBox.top,
  153. left: container.layoutBox.left,
  154. width: container.computedStyle.width,
  155. height: container.computedStyle.height,
  156. }
  157. const draw = new Draw(canvas, ctx)
  158. await draw.drawNode(container)
  159. return Promise.resolve(container)
  160. },
  161. canvasToTempFilePath(args = {}) {
  162. return new Promise((resolve, reject) => {
  163. const {
  164. top, left, width, height
  165. } = this.boundary
  166. wx.canvasToTempFilePath({
  167. x: left,
  168. y: top,
  169. width,
  170. height,
  171. destWidth: width * this.dpr,
  172. destHeight: height * this.dpr,
  173. canvas: this.canvas,
  174. fileType: args.fileType || 'png',
  175. quality: args.quality || 1,
  176. success: resolve,
  177. fail: reject
  178. })
  179. })
  180. }
  181. }
  182. })
  183. /***/ }),
  184. /* 1 */
  185. /***/ (function(module, exports) {
  186. /**
  187. * Module dependencies.
  188. */
  189. /**
  190. * Expose `parse`.
  191. */
  192. /**
  193. * Parse the given string of `xml`.
  194. *
  195. * @param {String} xml
  196. * @return {Object}
  197. * @api public
  198. */
  199. function parse(xml) {
  200. xml = xml.trim()
  201. // strip comments
  202. xml = xml.replace(/<!--[\s\S]*?-->/g, '')
  203. return document()
  204. /**
  205. * XML document.
  206. */
  207. function document() {
  208. return {
  209. declaration: declaration(),
  210. root: tag()
  211. }
  212. }
  213. /**
  214. * Declaration.
  215. */
  216. function declaration() {
  217. const m = match(/^<\?xml\s*/)
  218. if (!m) return
  219. // tag
  220. const node = {
  221. attributes: {}
  222. }
  223. // attributes
  224. while (!(eos() || is('?>'))) {
  225. const attr = attribute()
  226. if (!attr) return node
  227. node.attributes[attr.name] = attr.value
  228. }
  229. match(/\?>\s*/)
  230. return node
  231. }
  232. /**
  233. * Tag.
  234. */
  235. function tag() {
  236. const m = match(/^<([\w-:.]+)\s*/)
  237. if (!m) return
  238. // name
  239. const node = {
  240. name: m[1],
  241. attributes: {},
  242. children: []
  243. }
  244. // attributes
  245. while (!(eos() || is('>') || is('?>') || is('/>'))) {
  246. const attr = attribute()
  247. if (!attr) return node
  248. node.attributes[attr.name] = attr.value
  249. }
  250. // self closing tag
  251. if (match(/^\s*\/>\s*/)) {
  252. return node
  253. }
  254. match(/\??>\s*/)
  255. // content
  256. node.content = content()
  257. // children
  258. let child
  259. while (child = tag()) {
  260. node.children.push(child)
  261. }
  262. // closing
  263. match(/^<\/[\w-:.]+>\s*/)
  264. return node
  265. }
  266. /**
  267. * Text content.
  268. */
  269. function content() {
  270. const m = match(/^([^<]*)/)
  271. if (m) return m[1]
  272. return ''
  273. }
  274. /**
  275. * Attribute.
  276. */
  277. function attribute() {
  278. const m = match(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/)
  279. if (!m) return
  280. return {name: m[1], value: strip(m[2])}
  281. }
  282. /**
  283. * Strip quotes from `val`.
  284. */
  285. function strip(val) {
  286. return val.replace(/^['"]|['"]$/g, '')
  287. }
  288. /**
  289. * Match `re` and advance the string.
  290. */
  291. function match(re) {
  292. const m = xml.match(re)
  293. if (!m) return
  294. xml = xml.slice(m[0].length)
  295. return m
  296. }
  297. /**
  298. * End-of-source.
  299. */
  300. function eos() {
  301. return xml.length == 0
  302. }
  303. /**
  304. * Check for `prefix`.
  305. */
  306. function is(prefix) {
  307. return xml.indexOf(prefix) == 0
  308. }
  309. }
  310. module.exports = parse
  311. /***/ }),
  312. /* 2 */
  313. /***/ (function(module, exports, __webpack_require__) {
  314. const Block = __webpack_require__(3)
  315. const {splitLineToCamelCase} = __webpack_require__(4)
  316. class Element extends Block {
  317. constructor(prop) {
  318. super(prop.style)
  319. this.name = prop.name
  320. this.attributes = prop.attributes
  321. }
  322. }
  323. class Widget {
  324. constructor(xom, style) {
  325. this.xom = xom
  326. this.style = style
  327. this.inheritProps = ['fontSize', 'lineHeight', 'textAlign', 'verticalAlign', 'color']
  328. }
  329. init() {
  330. this.container = this.create(this.xom)
  331. this.container.layout()
  332. this.inheritStyle(this.container)
  333. return this.container
  334. }
  335. // 继承父节点的样式
  336. inheritStyle(node) {
  337. const parent = node.parent || null
  338. const children = node.children || {}
  339. const computedStyle = node.computedStyle
  340. if (parent) {
  341. this.inheritProps.forEach(prop => {
  342. computedStyle[prop] = computedStyle[prop] || parent.computedStyle[prop]
  343. })
  344. }
  345. Object.values(children).forEach(child => {
  346. this.inheritStyle(child)
  347. })
  348. }
  349. create(node) {
  350. let classNames = (node.attributes.class || '').split(' ')
  351. classNames = classNames.map(item => splitLineToCamelCase(item.trim()))
  352. const style = {}
  353. classNames.forEach(item => {
  354. Object.assign(style, this.style[item] || {})
  355. })
  356. const args = {name: node.name, style}
  357. const attrs = Object.keys(node.attributes)
  358. const attributes = {}
  359. for (const attr of attrs) {
  360. const value = node.attributes[attr]
  361. const CamelAttr = splitLineToCamelCase(attr)
  362. if (value === '' || value === 'true') {
  363. attributes[CamelAttr] = true
  364. } else if (value === 'false') {
  365. attributes[CamelAttr] = false
  366. } else {
  367. attributes[CamelAttr] = value
  368. }
  369. }
  370. attributes.text = node.content
  371. args.attributes = attributes
  372. const element = new Element(args)
  373. node.children.forEach(childNode => {
  374. const childElement = this.create(childNode)
  375. element.add(childElement)
  376. })
  377. return element
  378. }
  379. }
  380. module.exports = {Widget}
  381. /***/ }),
  382. /* 3 */
  383. /***/ (function(module, exports) {
  384. module.exports = require("../widget-ui/index");
  385. /***/ }),
  386. /* 4 */
  387. /***/ (function(module, exports) {
  388. const hex = (color) => {
  389. let result = null
  390. if (/^#/.test(color) && (color.length === 7 || color.length === 9)) {
  391. return color
  392. // eslint-disable-next-line no-cond-assign
  393. } else if ((result = /^(rgb|rgba)\((.+)\)/.exec(color)) !== null) {
  394. return '#' + result[2].split(',').map((part, index) => {
  395. part = part.trim()
  396. part = index === 3 ? Math.floor(parseFloat(part) * 255) : parseInt(part, 10)
  397. part = part.toString(16)
  398. if (part.length === 1) {
  399. part = '0' + part
  400. }
  401. return part
  402. }).join('')
  403. } else {
  404. return '#00000000'
  405. }
  406. }
  407. const splitLineToCamelCase = (str) => str.split('-').map((part, index) => {
  408. if (index === 0) {
  409. return part
  410. }
  411. return part[0].toUpperCase() + part.slice(1)
  412. }).join('')
  413. module.exports = {
  414. hex,
  415. splitLineToCamelCase
  416. }
  417. /***/ }),
  418. /* 5 */
  419. /***/ (function(module, exports) {
  420. class Draw {
  421. constructor(canvas, context) {
  422. this.canvas = canvas
  423. this.ctx = context
  424. }
  425. roundRect(x, y, w, h, r, fill = true, stroke = false) {
  426. if (r < 0) return
  427. const ctx = this.ctx
  428. ctx.beginPath()
  429. ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 3 / 2)
  430. ctx.arc(x + w - r, y + r, r, Math.PI * 3 / 2, 0)
  431. ctx.arc(x + w - r, y + h - r, r, 0, Math.PI / 2)
  432. ctx.arc(x + r, y + h - r, r, Math.PI / 2, Math.PI)
  433. ctx.lineTo(x, y + r)
  434. if (stroke) ctx.stroke()
  435. if (fill) ctx.fill()
  436. }
  437. drawView(box, style) {
  438. const ctx = this.ctx
  439. const {
  440. left: x, top: y, width: w, height: h
  441. } = box
  442. const {
  443. borderRadius = 0,
  444. borderWidth = 0,
  445. borderColor,
  446. color = '#000',
  447. backgroundColor = 'transparent',
  448. } = style
  449. ctx.save()
  450. // 外环
  451. if (borderWidth > 0) {
  452. ctx.fillStyle = borderColor || color
  453. this.roundRect(x, y, w, h, borderRadius)
  454. }
  455. // 内环
  456. ctx.fillStyle = backgroundColor
  457. const innerWidth = w - 2 * borderWidth
  458. const innerHeight = h - 2 * borderWidth
  459. const innerRadius = borderRadius - borderWidth >= 0 ? borderRadius - borderWidth : 0
  460. this.roundRect(x + borderWidth, y + borderWidth, innerWidth, innerHeight, innerRadius)
  461. ctx.restore()
  462. }
  463. async drawImage(img, box, style) {
  464. await new Promise((resolve, reject) => {
  465. const ctx = this.ctx
  466. const canvas = this.canvas
  467. const {
  468. borderRadius = 0
  469. } = style
  470. const {
  471. left: x, top: y, width: w, height: h
  472. } = box
  473. ctx.save()
  474. this.roundRect(x, y, w, h, borderRadius, false, false)
  475. ctx.clip()
  476. const Image = canvas.createImage()
  477. Image.onload = () => {
  478. ctx.drawImage(Image, x, y, w, h)
  479. ctx.restore()
  480. resolve()
  481. }
  482. Image.onerror = () => { reject() }
  483. Image.src = img
  484. })
  485. }
  486. // eslint-disable-next-line complexity
  487. drawText(text, box, style) {
  488. const ctx = this.ctx
  489. let {
  490. left: x, top: y, width: w, height: h
  491. } = box
  492. let {
  493. color = '#000',
  494. lineHeight = '1.4em',
  495. fontSize = 14,
  496. textAlign = 'left',
  497. verticalAlign = 'top',
  498. backgroundColor = 'transparent'
  499. } = style
  500. if (!text || (lineHeight > h)) return
  501. ctx.save()
  502. if (lineHeight) { // 2em
  503. lineHeight = Math.ceil(parseFloat(lineHeight.replace('em')) * fontSize)
  504. }
  505. ctx.textBaseline = 'top'
  506. ctx.font = `${fontSize}px sans-serif`
  507. ctx.textAlign = textAlign
  508. // 背景色
  509. ctx.fillStyle = backgroundColor
  510. this.roundRect(x, y, w, h, 0)
  511. // 文字颜色
  512. ctx.fillStyle = color
  513. // 水平布局
  514. switch (textAlign) {
  515. case 'left':
  516. break
  517. case 'center':
  518. x += 0.5 * w
  519. break
  520. case 'right':
  521. x += w
  522. break
  523. default: break
  524. }
  525. const textWidth = ctx.measureText(text).width
  526. const actualHeight = Math.ceil(textWidth / w) * lineHeight
  527. let paddingTop = Math.ceil((h - actualHeight) / 2)
  528. if (paddingTop < 0) paddingTop = 0
  529. // 垂直布局
  530. switch (verticalAlign) {
  531. case 'top':
  532. break
  533. case 'middle':
  534. y += paddingTop
  535. break
  536. case 'bottom':
  537. y += 2 * paddingTop
  538. break
  539. default: break
  540. }
  541. const inlinePaddingTop = Math.ceil((lineHeight - fontSize) / 2)
  542. // 不超过一行
  543. if (textWidth <= w) {
  544. ctx.fillText(text, x, y + inlinePaddingTop)
  545. return
  546. }
  547. // 多行文本
  548. const chars = text.split('')
  549. const _y = y
  550. // 逐行绘制
  551. let line = ''
  552. for (const ch of chars) {
  553. const testLine = line + ch
  554. const testWidth = ctx.measureText(testLine).width
  555. if (testWidth > w) {
  556. ctx.fillText(line, x, y + inlinePaddingTop)
  557. y += lineHeight
  558. line = ch
  559. if ((y + lineHeight) > (_y + h)) break
  560. } else {
  561. line = testLine
  562. }
  563. }
  564. // 避免溢出
  565. if ((y + lineHeight) <= (_y + h)) {
  566. ctx.fillText(line, x, y + inlinePaddingTop)
  567. }
  568. ctx.restore()
  569. }
  570. async drawNode(element) {
  571. const {layoutBox, computedStyle, name} = element
  572. const {src, text} = element.attributes
  573. if (name === 'view') {
  574. this.drawView(layoutBox, computedStyle)
  575. } else if (name === 'image') {
  576. await this.drawImage(src, layoutBox, computedStyle)
  577. } else if (name === 'text') {
  578. this.drawText(text, layoutBox, computedStyle)
  579. }
  580. const childs = Object.values(element.children)
  581. for (const child of childs) {
  582. await this.drawNode(child)
  583. }
  584. }
  585. }
  586. module.exports = {
  587. Draw
  588. }
  589. /***/ })
  590. /******/ ]);
  591. });
  592. export default global['__wxComponents']['wxml-to-canvas/index']
  593. </script>
  594. <style platform="mp-weixin">
  595. </style>