index.js 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505
  1. ; var QSCanvas = (function () {
  2. const platform = getPlatform(), isUni = platform == 'uni', isNode = platform == 'node',
  3. isWeb = platform == 'web', imgCache = {}, vmCache = {},
  4. asyncDrawWhiteList = Object.freeze(['init', 'initAsyncDrawMode', 'initArgs', 'initCanvas', 'handleCtx', 'initData',
  5. 'draw', 'toImage', 'updateCanvasWH', 'clear', 'restoreAsyncDrawMode']),
  6. calcMethods = Object.freeze(['setPaintbrush', 'setPaintbrushProp', 'resetPaintbrush', 'savePaintbrush',
  7. 'restorePaintbrush', 'calcText', 'calcImg', 'measureText', 'loadImage']),
  8. asyncDrawMethods = Object.freeze(['setPaintbrush', 'setPaintbrushProp', 'resetPaintbrush', 'savePaintbrush',
  9. 'restorePaintbrush', 'drawText', 'drawStraightLine', 'drawDoubleStraightLine', 'drawDotted',
  10. 'drawDottedStraightLine', 'drawLine', 'drawTextDecoration', 'drawImg', 'drawQrCode', 'setCircle', 'setRect']),
  11. allSelfMethods = Object.freeze(['setPaintbrush', 'setPaintbrushProp', 'resetPaintbrush', 'savePaintbrush',
  12. 'restorePaintbrush', 'drawText', 'drawStraightLine', 'drawDoubleStraightLine', 'drawDotted',
  13. 'drawDottedStraightLine', 'drawLine', 'drawTextDecoration', 'drawImg', 'drawQrCode', 'setCircle',
  14. 'setRect', 'calcText', 'calcImg', 'measureText', 'loadImage', 'drawArray', 'drawItem']),
  15. needReturnMethods = Object.freeze(['drawText', 'drawImg']),
  16. commonMethods = Object.freeze(["drawImage", "putImageData", "getImageData", "createImageData", "addPage", "save",
  17. "restore", "rotate", "translate", "transform", "getTransform", "resetTransform", "setTransform", "isPointInPath",
  18. "scale", "clip", "fill", "stroke", "fillText", "strokeText", "fillRect", "strokeRect", "clearRect", "rect",
  19. "measureText", "moveTo", "lineTo", "bezierCurveTo", "quadraticCurveTo", "beginPath", "closePath", "arc", "arcTo",
  20. "ellipse", "setLineDash", "getLineDash", "createPattern", "createLinearGradient", "createRadialGradient"])
  21. let nodeCanvas, id = 1
  22. // #ifndef APP-PLUS
  23. // #ifndef H5
  24. // #ifndef MP
  25. // #ifndef QUICKAPP-WEBVIEW
  26. // #ifndef QUICKAPP-WEBVIEW-UNION
  27. // #ifndef QUICKAPP-WEBVIEW-HUAWEI
  28. if (isNode) {
  29. try { nodeCanvas = require('canvas') }
  30. catch (e) { if (isNode) throw new Error('node环境依赖node-canvas!') }
  31. }
  32. // #endif
  33. // #endif
  34. // #endif
  35. // #endif
  36. // #endif
  37. // #endif
  38. /**
  39. * 判断是否是undefined, uni中的undefined不是字符串
  40. */
  41. function notUnd(t) {
  42. return String(t) != 'undefined'
  43. }
  44. function isNull(a) {
  45. return !((a || a == 0) && !['undefined', 'null'].includes(String(a)))
  46. }
  47. /**
  48. * 判断环境
  49. */
  50. function getPlatform() {
  51. if (notUnd(typeof uni)) return 'uni'
  52. if (notUnd(typeof window) && notUnd(typeof document)) return 'web'
  53. return 'node'
  54. }
  55. /**
  56. * 获取实例
  57. */
  58. function getCtx(vm, args) {
  59. if (isUni) {
  60. if (!args.canvasId) {
  61. throw new Error('canvasId 不能为空')
  62. }
  63. }
  64. let canvas, obj = {}
  65. switch (platform) {
  66. case 'uni':
  67. canvas = uni.createCanvasContext(args.canvasId, vm)
  68. obj.canvas = canvas;
  69. obj.ctx = canvas;
  70. break
  71. case 'web':
  72. canvas = args?.canvasId ? document.getElementById(args?.canvasId) : document.createElement('canvas')
  73. canvas.width = args?.width || 10
  74. canvas.height = args?.height || 10
  75. obj.canvas = canvas
  76. obj.ctx = canvas.getContext('2d')
  77. break
  78. case 'node':
  79. canvas = nodeCanvas.createCanvas(args?.width || 10, args?.height || 10)
  80. obj.canvas = canvas
  81. obj.ctx = canvas.getContext('2d')
  82. break
  83. }
  84. return obj
  85. }
  86. class QSCanvas {
  87. #nc
  88. constructor(obj, vm) {
  89. this._id = id++
  90. vmCache[this._id] = vm
  91. if(obj) {
  92. this.init(obj)
  93. }
  94. }
  95. init(obj = {}) {
  96. this.initArgs(obj).initData().initCanvas().handleCtx().resetPaintbrush()
  97. if(this._data.asyncDrawMode === true) {
  98. this.#nc = new QSCanvas({ asyncDrawMode: false })
  99. this.initAsyncDrawMode()
  100. }
  101. }
  102. initAsyncDrawMode() {
  103. if(isUni) return
  104. const ctxMethods = this._data.ctxMethods
  105. const arr = [...new Set([...allSelfMethods, ...ctxMethods])]
  106. for(let i = 0; i < arr.length; i++) {
  107. const item = arr[i]
  108. this.handleAsyncDrawModeItem(item)
  109. }
  110. }
  111. handleAsyncDrawModeItem(i) {
  112. if(isUni) return
  113. if(asyncDrawWhiteList.includes(i)) {
  114. console.log('白名单跳过')
  115. return
  116. }
  117. if(typeof this[i] == 'function') {
  118. if(!this._data.nMethods[i]) this._data.nMethods[i] = this[i]
  119. let _this = this
  120. this[i] = function () {
  121. let r
  122. if(calcMethods.includes(i)) {
  123. r = _this.#nc[i](...arguments)
  124. }
  125. if(r && r !== _this && r !== _this.#nc) return r
  126. if(asyncDrawMethods.includes(i) || _this._data.ctxMethods.includes(i) ) {
  127. _this._data.asyncDrawQueue.push({ method: i, args: arguments })
  128. }
  129. if(needReturnMethods.includes(i)) {
  130. return _this.#nc[i](...arguments)
  131. }
  132. }
  133. }
  134. }
  135. restoreAsyncDrawMode() {
  136. if(isUni) return
  137. const nMethods = this._data.nMethods
  138. for(const i in nMethods) {
  139. this[i] = nMethods[i]
  140. }
  141. }
  142. initArgs(obj = {}) {
  143. this._args = obj
  144. return this
  145. }
  146. initCanvas() {
  147. const canvasObj = getCtx(vmCache[this._id], this._args)
  148. this.canvas = canvasObj.canvas
  149. this.ctx = canvasObj.ctx
  150. return this
  151. }
  152. /**
  153. * 使QSCanvas拥有原有方法
  154. */
  155. handleCtx() {
  156. const ctx = this.ctx
  157. const active = (i)=>{
  158. this._data.ctxMethods.push(i)
  159. this[i] =
  160. ctx[i].bind(ctx)
  161. return
  162. function a() {
  163. return ctx[i](...arguments)
  164. }
  165. }
  166. for (const i in ctx) {
  167. if (typeof ctx[i] == 'function') {
  168. if (!this[i]) {
  169. active(i)
  170. }
  171. }
  172. }
  173. for(let k = 0; k < commonMethods.length; k++) {
  174. const i = commonMethods[k]
  175. if (typeof ctx[i] == 'function') {
  176. if (!this[i]) {
  177. active(i)
  178. }
  179. }
  180. }
  181. return this
  182. }
  183. initData() {
  184. this._data = {
  185. oldPaintbrushProps: {}, savedPaintbrushProps: [],
  186. font: { fontStyle: 'normal', fontVariant: 'normal', fontWeight: 'normal', fontSize: 10, fontFamily: 'sans-serif' },
  187. height: this._args.height || 10, width: this._args.width || 10,
  188. whChange: false,
  189. asyncDrawQueue: [],
  190. nMethods: {},
  191. asyncDrawMode: (isNode || isWeb)?this._args.asyncDrawMode !== false:false,
  192. ctxMethods: []
  193. }
  194. return this
  195. }
  196. /**
  197. * 设置画笔
  198. */
  199. setPaintbrush(obj = {}) {
  200. filterPaintbrushProps(obj);
  201. for (const k in obj) {
  202. this.setPaintbrushProp(k, obj[k])
  203. }
  204. return this
  205. }
  206. /**
  207. * 设置画笔操作兼容uni
  208. */
  209. setPaintbrushProp(prop, data) {
  210. if (isNull(prop) || isNull(data)) return;
  211. prop = hyphen2Hump(prop)
  212. const ctx = this.ctx;
  213. if (prop == 'font') {
  214. if (data) {
  215. if (typeof data != 'object') {
  216. console.warn('font属性需Object格式')
  217. return
  218. }
  219. for (const k in data) if (isNull(data[k])) delete (data[k])
  220. const font = { ...this._data.font, ...data }
  221. if(isUni) font.fontSize = Math.round(font.fontSize)
  222. this._data.font = font
  223. const f = this._data.font
  224. this._data.oldPaintbrushProps[prop] = f;
  225. const setFont = ()=>{
  226. ctx.font = `${f.fontStyle || 'normal'} ${f.fontVariant || 'normal'} ${f.fontWeight || 'normal'} ${f.fontSize ?? 10}px ${f.fontFamily || 'sans-serif'}`
  227. }
  228. if(isUni) {
  229. // #ifdef MP-TOUTIAO
  230. ctx.setFontSize(f.fontSize)
  231. // #endif
  232. // #ifndef MP-TOUTIAO
  233. setFont()
  234. // #endif
  235. }else setFont()
  236. }
  237. } else {
  238. this._data.oldPaintbrushProps[prop] = data;
  239. const fnn = 'set' + prop[0].toUpperCase() + prop.slice(1);
  240. if (typeof ctx?.[fnn] == 'function') {
  241. ctx[fnn](data);
  242. }
  243. else {
  244. ctx[prop] = data;
  245. }
  246. }
  247. return this
  248. }
  249. /**
  250. * 重置画笔
  251. */
  252. resetPaintbrush(obj = {}) {
  253. this.setPaintbrush({
  254. fillStyle: '#000000',
  255. strokeStyle: '#000000',
  256. shadowColor: '#000000',
  257. shadowBlur: 0,
  258. shadowOffsetX: 0,
  259. shadowOffsetY: 0,
  260. lineCap: 'butt',
  261. lineJoin: 'miter',
  262. lineWidth: 1,
  263. miterLimit: 10,
  264. font: this._data.font,
  265. textAlign: 'start',
  266. textBaseline: 'top',
  267. globalAlpha: 1.0,
  268. globalCompositeOperation: 'source-over',
  269. ...obj
  270. })
  271. return this
  272. }
  273. saveAndSetPaintbrush(paintbrushProps = {}) {
  274. this.savePaintbrush()
  275. this.setPaintbrush(paintbrushProps)
  276. return this
  277. }
  278. /**
  279. * 保存画笔设置
  280. */
  281. savePaintbrush() {
  282. this._data.savedPaintbrushProps.unshift({ ...this._data.oldPaintbrushProps })
  283. return this
  284. }
  285. /**
  286. * 恢复上次保存的画笔设置
  287. */
  288. restorePaintbrush() {
  289. const savedProps = this._data.savedPaintbrushProps.shift()
  290. if (savedProps) this._data.oldPaintbrushProps = { ...this._data.oldPaintbrushProps, ...savedProps }
  291. this.resetPaintbrush({ ...this._data.oldPaintbrushProps })
  292. return this
  293. }
  294. /**
  295. * 更新画布宽高
  296. */
  297. updateCanvasWH(obj = {}) {
  298. let { width, height, delay } = obj, setCanvasWH = this._args?.setCanvasWH
  299. width = width || this._data?.width || 10
  300. height = height || this._data?.height || 10
  301. return new Promise((rs, rj) => {
  302. if (isUni) {
  303. if (!setCanvasWH || typeof setCanvasWH != 'function') {
  304. rj('setCanvasWH异常, uni-app 请在初始化时传入setCanvasWH函数')
  305. return
  306. }
  307. setCanvasWH({ height, width })
  308. setTimeout(() => {
  309. rs()
  310. }, delay ?? 50)
  311. } else {
  312. this.canvas.height = height
  313. this.canvas.width = width
  314. rs()
  315. }
  316. }).then(r => {
  317. if (this._data.width != width || this._data.height != height) {
  318. this._data.whChange = true
  319. }
  320. this._data.width = width
  321. this._data.height = height
  322. if(!this._data.asyncDrawMode) this.resetPaintbrush(this._data.oldPaintbrushProps)
  323. })
  324. }
  325. /**
  326. * 清除画布内容
  327. */
  328. clear() {
  329. this.ctx.clearRect(0, 0, this._data.width || 999999, this._data.height || 999999)
  330. return this
  331. }
  332. /**
  333. * 兼容uni draw
  334. */
  335. draw(obj = {}) {
  336. const { reserve } = obj
  337. return new Promise((rs, rj) => {
  338. if (isUni) {
  339. let done = false
  340. const settimeoutkey = setTimeout(()=>{
  341. if(!done) {
  342. rs()
  343. }else{
  344. clearTimeout(settimeoutkey)
  345. }
  346. }, 3000)
  347. this.ctx.draw(reserve ?? false, ()=>{
  348. done = true
  349. clearTimeout(settimeoutkey)
  350. rs()
  351. })
  352. } else {
  353. if(this._data.asyncDrawMode) {
  354. if(reserve !== true) this.clear()
  355. this.restoreAsyncDrawMode()
  356. this.resetPaintbrush()
  357. const arr = this._data.asyncDrawQueue
  358. new Promise(async(resolve, reject)=>{
  359. for(let i = 0; i < arr.length; i++) {
  360. const item = arr[i]
  361. try {
  362. const r = this[item.method].call(this, ...item.args)
  363. if(typeof r?.then == 'function') await r
  364. } catch (error) {
  365. reject(error)
  366. return
  367. }
  368. }
  369. resolve()
  370. })
  371. .then(()=>{
  372. this._data.asyncDrawQueue = []
  373. this.initAsyncDrawMode()
  374. rs()
  375. })
  376. .catch(err=>{
  377. this.initAsyncDrawMode()
  378. rj(err)
  379. })
  380. }else{
  381. rs()
  382. }
  383. }
  384. })
  385. }
  386. /**
  387. * canvas2image
  388. */
  389. toImage(obj = {}) {
  390. return new Promise((rs, rj) => {
  391. if (isUni) {
  392. const canvasId = this._args.canvasId
  393. if (!canvasId) {
  394. rj('canvasId不存在')
  395. return
  396. }
  397. uni.canvasToTempFilePath({
  398. ...obj,
  399. canvasId: canvasId,
  400. success: r => {
  401. obj.success?.(r)
  402. rs(r.tempFilePath)
  403. },
  404. fail: err => {
  405. obj.fail?.(err)
  406. rj(err)
  407. }
  408. }, vmCache[this._id])
  409. } else {
  410. rs(this.canvas.toDataURL(`image/${['jpg', 'jpeg'].includes(obj.fileType) ? 'jpeg' : 'png'
  411. }`, obj.quality ?? 1))
  412. }
  413. })
  414. }
  415. /**
  416. * 计算文字多行
  417. */
  418. calcText(obj = {}) {
  419. const line = obj.line || -1
  420. return new Promise((rs, rj) => {
  421. try {
  422. this.saveAndSetPaintbrush({
  423. ...(obj.paintbrushProps || {})
  424. })
  425. const mt = this.measureText
  426. let splitTexts = [], str = obj.val, width = 0
  427. function run(text, endLine) {
  428. let endLineWidth = 0
  429. const textWidth = mt(text).width
  430. if (endLine) {
  431. if (textWidth < obj.maxWidth || text.length < 2) {
  432. return { index: text.length, ellipsis: false, width: textWidth }
  433. }else{
  434. endLineWidth = mt('...').width
  435. }
  436. }
  437. const textWidthEndLineWidth = textWidth + endLineWidth
  438. if (textWidthEndLineWidth < obj.maxWidth || text.length < 2) {
  439. return { index: text.length, ellipsis: false, width: textWidthEndLineWidth }
  440. }
  441. let loop = true, mid = Math.floor((text.length + 1) / 2), oldMid = 1, mode = '', tw
  442. while (loop) {
  443. if (mid <= 1) {
  444. loop = false
  445. break
  446. }
  447. if (mid > text.length) {
  448. mid = text.length
  449. loop = false
  450. break
  451. }
  452. const t = text.substr(0, mid)
  453. tw = mt(t).width + endLineWidth
  454. if (tw > obj.maxWidth) {
  455. text = t
  456. if ((mode == 'xy' && Math.abs(oldMid - mid) < 1)) {
  457. loop = false
  458. } else {
  459. mode = 'dy'
  460. oldMid = mid
  461. mid = Math.floor((t.length + 1) / 2)
  462. }
  463. } else if (tw == obj.maxWidth) {
  464. loop = false
  465. } else {
  466. if (mid <= 1 || (Math.abs(oldMid - mid) < 1)) {
  467. loop = false
  468. } else {
  469. mode = 'xy'
  470. oldMid = mid
  471. mid += Math.floor((text.length - mid) / 2)
  472. }
  473. }
  474. }
  475. return { index: mid, ellipsis: endLine, width: tw }
  476. }
  477. const font = {...this._data.font}
  478. if(obj.maxWidth) {
  479. let i = 0
  480. while (str.length) {
  481. const endLine = line > 0 && splitTexts.length + 1 >= line, {index:len, ellipsis, width} = run(str, endLine);
  482. const txt = str.substr(0, len)
  483. splitTexts.push({ ...obj, val: txt, y: i ? obj.y + (font.fontSize + (obj.lineHeight || 0)) * i : obj.y, width })
  484. if (endLine) {
  485. if(ellipsis)splitTexts[splitTexts.length - 1].val += '...'
  486. str = ''
  487. }
  488. else
  489. str = str.slice(len)
  490. i++
  491. }
  492. width = splitTexts.length == 1?splitTexts[0].width:splitTexts.length > 1?obj.maxWidth:0
  493. }else{
  494. splitTexts = [obj]
  495. width = mt(obj.val).width
  496. }
  497. this.restorePaintbrush()
  498. rs({
  499. ...obj, calcTexts: splitTexts, _calc: true,
  500. left: obj.x, top: obj.y, right: obj.x + width, bottom: (splitTexts[splitTexts.length - 1].y + font.fontSize),
  501. width: width, height: (splitTexts[splitTexts.length - 1].y + font.fontSize) - obj.y , fontSize: font.fontSize
  502. })
  503. } catch (error) {
  504. rj(error)
  505. }
  506. })
  507. }
  508. /* 绘制 */
  509. /**
  510. * 绘制文本
  511. */
  512. drawText(obj = {}) {
  513. return new Promise(async (rs, rj) => {
  514. try {
  515. if (!obj.val) {
  516. console.warn(`需绘制的文本为空`)
  517. rs()
  518. return
  519. }
  520. this.saveAndSetPaintbrush({
  521. ...(obj.paintbrushProps || {})
  522. })
  523. const ft = (obj) => {
  524. this.fillText(obj.val, obj.x, obj.y)
  525. },
  526. ftItem = (item) => {
  527. ft(item)
  528. if (item.textDecoration) this.drawTextDecoration(item)
  529. }
  530. const calcR = obj._calc?obj:await this.calcText(obj)
  531. for (let i = 0; i < calcR.calcTexts.length; i++) {
  532. ftItem(calcR.calcTexts[i])
  533. }
  534. this.restorePaintbrush()
  535. rs(calcR)
  536. } catch (error) {
  537. rj(error)
  538. }
  539. })
  540. }
  541. drawStraightLine(obj = {}) {
  542. const { x1, y1, x2, y2, paintbrushProps } = obj, ctx = this.ctx
  543. ctx.beginPath()
  544. ctx.moveTo(x1, y1)
  545. ctx.lineTo(x2, y2)
  546. this.saveAndSetPaintbrush(paintbrushProps || {})
  547. ctx.stroke()
  548. this.restorePaintbrush()
  549. }
  550. drawDoubleStraightLine(obj = {}) {
  551. let { gap } = obj
  552. gap = gap ?? 1
  553. this.drawStraightLine(obj)
  554. this.drawStraightLine({ ...obj, y1: obj.y1 + gap, y2: obj.y2 + gap })
  555. }
  556. drawDotted(obj = {}) {
  557. this.setCircle(obj)
  558. if(obj.clip) obj.clip = false
  559. this.saveAndSetPaintbrush(obj.paintbrushProps || {})
  560. this.ctx.fill()
  561. this.restorePaintbrush()
  562. }
  563. drawDottedStraightLine(obj = {}) {
  564. let { x1, x2, y1, y2, gap, width, paintbrushProps } = obj
  565. x2 = x2 - width
  566. gap = gap || 1
  567. const len = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2))
  568. const points = getPoints(x1, y1, x2, y2, Math.floor((len - gap) / (width + gap)), 9999999999)
  569. this.saveAndSetPaintbrush(paintbrushProps)
  570. this.drawDotted({ x: x1, y: y1, d: width })
  571. for (let i = 0; i < points.length; i++)
  572. this.drawDotted({ x: points[i][0], y: points[i][1], d: width })
  573. this.drawDotted({ x: x2, y: y2, d: width })
  574. this.restorePaintbrush()
  575. }
  576. drawLine(obj = {}) {
  577. const { style } = obj
  578. switch (style) {
  579. case 'double':
  580. obj.gap = (obj.width || 1) * 1.5
  581. this.drawDoubleStraightLine(obj)
  582. break
  583. case 'solide':
  584. this.drawStraightLine(obj)
  585. break
  586. case 'dotted':
  587. obj.gap = (obj.gap || 1) * 1.5
  588. obj.paintbrushProps = { fillStyle: obj.color }
  589. this.drawDottedStraightLine(obj)
  590. break
  591. }
  592. }
  593. /**
  594. * {
  595. ...(drawText属性),
  596. textDecoration: {
  597. line, //类型 同css text-decoration-line
  598. color, //线颜色
  599. width, //线宽度
  600. * }
  601. * }
  602. */
  603. drawTextDecoration(obj = {}) {
  604. this.savePaintbrush()
  605. const oldProps = this._data.oldPaintbrushProps, tw = this.measureText(obj.val).width, tD = obj.textDecoration, line = tD.line || 'line-through', color = tD.color || obj.color || oldProps.fillStyle || '#000000', width = tD.thickness || tD.width || (obj.fontSize ? obj.fontSize * 0.1 : false) || 1, style = tD.style || 'solide', offset = tD.offset || 0, gap = tD.gap ?? 1, fontSize = (obj.fontSize || this._data.font.fontSize)
  606. this.setPaintbrush({ lineWidth: width, strokeStyle: color })
  607. let y = 0
  608. switch (line) {
  609. case 'line-through':
  610. y = obj.y + fontSize / 2 - width / 2
  611. break
  612. case 'underline':
  613. y = obj.y + fontSize
  614. break
  615. case 'overline':
  616. y = obj.y
  617. break
  618. }
  619. switch (oldProps.textBaseline) {
  620. case 'top':
  621. y += width / 2
  622. break
  623. case 'bottom':
  624. y -= fontSize
  625. break
  626. case 'center':
  627. y -= fontSize / 2
  628. break
  629. }
  630. y += offset
  631. switch (line) {
  632. case 'line-through':
  633. case 'underline':
  634. case 'overline':
  635. this.drawLine({ x1: obj.x, y1: y, x2: obj.x + tw, y2: y, style, gap, width, color })
  636. break
  637. }
  638. this.restorePaintbrush()
  639. }
  640. /**
  641. * 绘制图片
  642. */
  643. drawImg(obj = {}) {
  644. return new Promise(async (rs, rj) => {
  645. try {
  646. if (!obj.val) {
  647. console.warn(`需绘制的图片为空`)
  648. rs()
  649. return
  650. }
  651. const calcR = obj._calc?obj:await this.calcImg(obj)
  652. if(calcR?.drawImageArgs && Array.isArray(calcR.drawImageArgs)) this.ctx.drawImage(...(calcR?.drawImageArgs || []))
  653. rs(calcR)
  654. } catch (error) {
  655. rj(error)
  656. }
  657. })
  658. }
  659. calcImg(obj = {}) {
  660. return new Promise(async (rs, rj)=>{
  661. try {
  662. if (!obj.val) {
  663. console.warn(`需绘制的图片为空`)
  664. rs()
  665. return
  666. }
  667. const img = await this.loadImage(obj.val), mode = obj.mode || 'scaleToFill'
  668. let arr, x = obj.x || 0, y = obj.y || 0, w = obj.width || 0, h = obj.height || 0, sw = img.width, sh = img.height, sx = 0, sy = 0
  669. const get_6 = ()=>{
  670. if(isUni) {
  671. // #ifdef MP-BAIDU
  672. return [x, y, w, h, sx, sy, sw, sh]
  673. // #endif
  674. }
  675. return [sx, sy, sw, sh, x, y, w, h]
  676. }
  677. switch(mode) {
  678. case 'aspectFit':
  679. h = img.height / img.width * w
  680. if (h < obj.height) {
  681. y = Number(obj.y) + obj.height / 2 - h/2
  682. } else {
  683. h = obj.height
  684. w = img.width / img.height * h
  685. x = Number(obj.x) + obj.width / 2 - w/2
  686. }
  687. arr = get_6()
  688. break
  689. case 'aspectFill':
  690. h = img.height / img.width * w
  691. if (h < obj.height) {
  692. h = obj.height
  693. sx = img.width / img.height * obj.height
  694. sx = (sx - obj.width) / sx * img.width / 2
  695. sw = img.width - sx * 2
  696. } else {
  697. sy = (h - obj.height) / h * img.height / 2
  698. sh = img.height - sy * 2
  699. }
  700. w = obj.width
  701. h = obj.height
  702. arr = get_6()
  703. break
  704. case 'widthFix':
  705. h = obj.height = img.height / img.width * obj.width
  706. arr = [x, y, w, h]
  707. break
  708. case 'heightFix':
  709. w = obj.width = img.width / img.height * obj.height
  710. arr = [x, y, w, h]
  711. break
  712. default:
  713. arr = [x, y, w, h]
  714. }
  715. arr.unshift(isUni ? img.toString() : img)
  716. rs({ ...obj, drawImageArgs: [...arr], img, left: obj.x, top: obj.y, right: obj.x + obj.width, bottom: obj.y + obj.height, _calc: true })
  717. } catch (error) {
  718. rj(error)
  719. }
  720. })
  721. }
  722. /**
  723. * 绘制二维码
  724. * 诗小柒 的二维码生成器代码
  725. */
  726. drawQrCode(obj = {}) {
  727. return new Promise((rs, rj) => {
  728. if (!obj?.val) {
  729. console.warn("绘制二维码val为空")
  730. rs()
  731. return
  732. }
  733. this.savePaintbrush()
  734. let qrcodeAlgObjCache = [];
  735. let options = {
  736. text: String(obj.val || '') || '', // 生成内容
  737. size: Number(obj.size || 0) || 200, // 二维码大小
  738. background: String(obj.background || '') || '#ffffff', // 背景色
  739. foreground: String(obj.foreground || '') || '#000000', // 前景色
  740. pdground: String(obj.pdground || '') || '#000000', // 定位角点颜色
  741. correctLevel: Number(obj.correctLevel || 0) || 3, // 容错级别
  742. dx: Number(obj.x || 0) || 0, // x轴距离
  743. dy: Number(obj.y || 0) || 0 // y轴距离
  744. }
  745. let qrCodeAlg = null;
  746. let d = 0;
  747. for (var i = 0, l = qrcodeAlgObjCache.length; i < l; i++) {
  748. d = i;
  749. if (qrcodeAlgObjCache[i].text == options.text && qrcodeAlgObjCache[i].text.correctLevel == options.correctLevel) {
  750. qrCodeAlg = qrcodeAlgObjCache[i].obj;
  751. break;
  752. }
  753. }
  754. if (d == l) {
  755. qrCodeAlg = new QRCodeAlg(options.text, options.correctLevel);
  756. qrcodeAlgObjCache.push({
  757. text: options.text,
  758. correctLevel: options.correctLevel,
  759. obj: qrCodeAlg
  760. });
  761. }
  762. let getForeGround = function (config) {
  763. let options = config.options;
  764. if (options.pdground && (
  765. (config.row > 1 && config.row < 5 && config.col > 1 && config.col < 5) ||
  766. (config.row > (config.count - 6) && config.row < (config.count - 2) && config.col > 1 && config
  767. .col < 5) ||
  768. (config.row > 1 && config.row < 5 && config.col > (config.count - 6) && config.col < (config.count -
  769. 2))
  770. )) {
  771. return options.pdground;
  772. }
  773. return options.foreground;
  774. }
  775. let count = qrCodeAlg.getModuleCount();
  776. let ratioSize = options.size;
  777. let tileW = (ratioSize / count);
  778. let tileH = (ratioSize / count);
  779. for (let row = 0; row < count; row++) {
  780. for (let col = 0; col < count; col++) {
  781. let w = (((col + 1) * tileW) - (col * tileW));
  782. let h = (((row + 1) * tileW) - (row * tileW));
  783. let foreground = getForeGround({
  784. row: row,
  785. col: col,
  786. count: count,
  787. options: options
  788. });
  789. this.setPaintbrush({ fillStyle: qrCodeAlg.modules[row][col] ? foreground : options.background });
  790. this.ctx.fillRect(options.dx + (col * tileW), options.dy + (row * tileH), w, h);
  791. }
  792. }
  793. this.restorePaintbrush()
  794. rs({...obj, height: obj.size, width: obj.size, left: obj.x, top: obj.y, right: obj.x + obj.width, bottom: obj.y + obj.size});
  795. })
  796. }
  797. /**
  798. * 圆形
  799. */
  800. setCircle(obj = {}) {
  801. const ctx = this.ctx
  802. let { x, y, d, mode } = obj
  803. mode = mode || 'leftTop'
  804. const r = d / 2
  805. if (obj.clip) ctx.save()
  806. ctx.beginPath();
  807. switch (mode) {
  808. case 'leftTop':
  809. ctx.arc(x + r, y + r, r, 0, 2 * Math.PI);
  810. break
  811. case 'center':
  812. ctx.arc(x, y, r, 0, 2 * Math.PI);
  813. break
  814. }
  815. ctx.closePath();
  816. if (obj.clip) ctx.clip()
  817. return this
  818. }
  819. /**
  820. * 矩形
  821. */
  822. setRect(obj = {}) {
  823. const ctx = this.ctx
  824. const { x, y, r, height, width } = obj
  825. if (obj.clip) ctx.save()
  826. ctx.beginPath();
  827. if (r && r > 0) {
  828. ctx.arc(x + r, y + r, r, 1 * Math.PI, 1.5 * Math.PI);
  829. ctx.lineTo(x + width - r, y);
  830. ctx.arc(x + width - r, y + r, r, 1.5 * Math.PI, 0);
  831. ctx.lineTo(x + width, y + height - r);
  832. ctx.arc(x + width - r, y + height - r, r, 0, .5 * Math.PI);
  833. ctx.lineTo(x + r, y + height);
  834. ctx.arc(x + r, y + height - r, r, .5 * Math.PI, 1 * Math.PI);
  835. ctx.lineTo(x, y + r);
  836. } else {
  837. ctx.moveTo(x, y);
  838. ctx.lineTo(x + width, y);
  839. ctx.lineTo(x + width, y + height);
  840. ctx.lineTo(x, y + height);
  841. ctx.lineTo(x, y);
  842. }
  843. ctx.closePath();
  844. if (obj.clip) ctx.clip()
  845. return this
  846. }
  847. /**
  848. * 加载图片
  849. */
  850. loadImage(url) {
  851. return new Promise(async (resolve, reject) => {
  852. if (!url) {
  853. console.warn('加载图片url为空')
  854. resolve()
  855. return
  856. }
  857. if (imgCache[url]) {
  858. resolve(imgCache[url])
  859. return
  860. }
  861. let img
  862. try {
  863. switch (platform) {
  864. case 'uni':
  865. img = await new Promise((rs, rj) => {
  866. if (url._loaded) {
  867. rs(url)
  868. return
  869. }
  870. if(~url.indexOf('data:image')) {
  871. let tempFilePath = url, imageInfoR = {}
  872. // #ifndef MP-ALIPAY
  873. imgTools.base64ToPath(url)
  874. .then(t=>{
  875. tempFilePath = t
  876. // #ifndef MP-BAIDU
  877. uni.getImageInfo({
  878. src: tempFilePath,
  879. success: imgInfo => {
  880. imageInfoR = imgInfo
  881. // #endif
  882. // #endif
  883. const uniImg = new String(tempFilePath)
  884. for (const i in imageInfoR) uniImg[i] = imageInfoR[i]
  885. uniImg._loaded = true
  886. rs(uniImg)
  887. // #ifndef MP-ALIPAY
  888. // #ifndef MP-BAIDU
  889. },
  890. fail: (err) => rj(err)
  891. })
  892. // #endif
  893. })
  894. .catch(err=>{
  895. rj(err)
  896. })
  897. // #endif
  898. }else if(url.substr(0, 4) == 'http'){
  899. uni.downloadFile({
  900. url: url,
  901. success: ({ tempFilePath }) => {
  902. uni.getImageInfo({
  903. src: tempFilePath,
  904. success: imageInfoR => {
  905. const uniImg = new String(tempFilePath)
  906. for (const i in imageInfoR) uniImg[i] = imageInfoR[i]
  907. uniImg._loaded = true
  908. rs(uniImg)
  909. },
  910. fail: (err) => rj(err)
  911. })
  912. },
  913. fail: (error) => rj(error)
  914. })
  915. }else{
  916. uni.getImageInfo({
  917. src: url,
  918. success: imageInfoR => {
  919. const uniImg = new String(url)
  920. for (const i in imageInfoR) uniImg[i] = imageInfoR[i]
  921. uniImg._loaded = true
  922. rs(uniImg)
  923. },
  924. fail: (err) => rj(err)
  925. })
  926. }
  927. });
  928. break
  929. case 'web':
  930. img = await new Promise((rs, rj) => {
  931. /* url instanceof Image */
  932. if (typeof url != 'string') {
  933. rs(url)
  934. return
  935. }
  936. // node 也可以用这种方式
  937. const imgObj = new Image()
  938. imgObj.onload = () => {
  939. rs(imgObj)
  940. }
  941. imgObj.onerror = err => {
  942. rj(err)
  943. }
  944. imgObj.src = url
  945. })
  946. break
  947. case 'node':
  948. img = await new Promise((rs, rj) => {
  949. /* url instanceof nodeCanvas.Image */
  950. if (typeof url != 'string') {
  951. rs(url)
  952. return
  953. }
  954. nodeCanvas.loadImage(url)
  955. .then(res => {
  956. rs(res)
  957. })
  958. .catch(err => {
  959. rj(err)
  960. })
  961. })
  962. break
  963. }
  964. } catch (error) {
  965. reject(error)
  966. }
  967. imgCache[url] = img
  968. resolve(img)
  969. })
  970. }
  971. drawArray(data) {
  972. return new Promise(async (rs, rj)=>{
  973. try {
  974. if(!data) {
  975. rj('drawArray需绘制参数不存在')
  976. return
  977. }
  978. if(!Array.isArray(data)) {
  979. rj('drawArray参数需要是Array')
  980. return
  981. }
  982. data = [...data].sort((a, b)=>(a?.zIndex ?? 0) - (b?.zIndex ?? 0))
  983. const arr = []
  984. for(let i = 0; i < data.length; i++) {
  985. const item = data[i]
  986. let r
  987. switch(typeof item) {
  988. case 'function':
  989. r = item()
  990. if(typeof r?.then == 'function') r = await r
  991. break
  992. case 'object':
  993. if(Array.isArray(item)) r = await this.drawArray(item)
  994. else r = await this.drawItem(item)
  995. break
  996. }
  997. arr.push({ item: item, result: r})
  998. }
  999. rs(arr)
  1000. } catch (error) {
  1001. rj(error)
  1002. }
  1003. })
  1004. }
  1005. drawItem(obj = {}) {
  1006. return new Promise(async (rs, rj)=>{
  1007. try {
  1008. let r
  1009. switch(obj.type) {
  1010. case 'text':
  1011. r = await this.drawText(obj)
  1012. break
  1013. case 'image':
  1014. r = await this.drawImg(obj)
  1015. break
  1016. case 'qrcode':
  1017. r = await this.drawQrCode(obj)
  1018. break
  1019. case 'method':
  1020. r = this[obj.name]?.(...(obj.data?Array.isArray(obj.data)?obj.data:[obj.data]:[]))
  1021. if(typeof r?.then == 'function') r = await r
  1022. break
  1023. case 'function':
  1024. r = obj.val?.()
  1025. if(typeof r?.then == 'function') r = await r
  1026. break
  1027. }
  1028. rs(r)
  1029. } catch (error) {
  1030. rj(error)
  1031. }
  1032. })
  1033. }
  1034. drawRichText(html) {
  1035. return new Promise(async (rs, rj)=>{
  1036. if(!html) {
  1037. rj('drawRichText需绘制参数不存在')
  1038. return
  1039. }
  1040. if(typeof html == 'string') html = htmlParse(html)
  1041. const result = []
  1042. function run(arr, parent) {
  1043. return new Promise(async (res, rej)=>{
  1044. for(let i = 0; i < arr.length; i++) {
  1045. const item = arr[i]
  1046. if(item.type == 'text') {
  1047. }else{
  1048. switch(item.name) {
  1049. case 'img':
  1050. break
  1051. }
  1052. }
  1053. result.push(item)
  1054. if(item.children?.length) {
  1055. item.__handle = function(obj) {
  1056. }
  1057. try {
  1058. await run(item.children, item)
  1059. } catch (error) {
  1060. rej(error)
  1061. return
  1062. }
  1063. }
  1064. }
  1065. res(result)
  1066. })
  1067. }
  1068. try {
  1069. rs({ html: html, htmlParses: await run(html) })
  1070. } catch (error) {
  1071. rj(error)
  1072. }
  1073. })
  1074. }
  1075. }
  1076. function filterPaintbrushProps(obj) {
  1077. switch (obj?.textBaseline) {
  1078. case 'normal':
  1079. if (isUni) obj.textBaseline = 'alphabetic'
  1080. break
  1081. case 'hanging':
  1082. if (isUni) obj.textBaseline = 'top'
  1083. break
  1084. case 'ideographic':
  1085. if (isUni) obj.textBaseline = 'bottom'
  1086. break
  1087. }
  1088. switch (obj?.textAlign) {
  1089. case 'start':
  1090. obj.textAlign = 'left'
  1091. break
  1092. case 'end':
  1093. obj.textAlign = 'right'
  1094. break
  1095. }
  1096. }
  1097. /**
  1098. * 驼峰转连字符
  1099. */
  1100. function hump2Hyphen(s) {
  1101. return s.replace(/([A-Z])/g, '-$1').toLowerCase()
  1102. }
  1103. /**
  1104. * 连字符转驼峰
  1105. */
  1106. function hyphen2Hump(s) {
  1107. if(!s) return ''
  1108. const arr= s.split("-");
  1109. for(var i=1;i<arr.length;i++){
  1110. arr[i]=arr[i].charAt(0).toUpperCase()+arr[i].substring(1);
  1111. }
  1112. return arr.join("");
  1113. }
  1114. /**
  1115. * 原文链接:https://blog.csdn.net/kingviewer/article/details/120346353
  1116. * 获取指定两点间圆弧上的点
  1117. * @param x1 起点经度
  1118. * @param y1 起点纬度
  1119. * @param x2 终点经度
  1120. * @param y2 终点纬度
  1121. * @param pointCount 要获取的点的数量
  1122. * @param level 弧度大小标定值,0~∞ 0为半圆,越大越接近直线
  1123. * @returns {*[x, y]} 从起点到终点的顺序排列的结果点经纬度数组
  1124. */
  1125. function getPoints(x1, y1, x2, y2, pointCount, level) {
  1126. let a, b, rSquare, k, kv, points = [];
  1127. if (x1 === x2) {
  1128. a = x1 + (y2 - y1) * level
  1129. b = y1 + (y2 - y1) / 2;
  1130. rSquare = (x1 - a) ** 2 + (y1 - b) ** 2;
  1131. } else if (y1 === y2) {
  1132. a = x1 + (x2 - x1) / 2;
  1133. b = y1 - (x2 - x1) * level
  1134. rSquare = (x1 - a) ** 2 + (y1 - b) ** 2;
  1135. } else {
  1136. let xc = (x1 + x2) / 2, yc = (y1 + y2) / 2,
  1137. lenSquare = ((x2 - x1) ** 2 + (y2 - y1) ** 2) * (level ** 2);
  1138. k = (x2 - x1) / (y1 - y2);
  1139. let l = yc - k * xc;
  1140. let a1 = 1 + k ** 2, b1 = 2 * k * (l - yc) - 2 * xc, c1 = xc ** 2 + (l - yc) ** 2 - lenSquare;
  1141. kv = -1 / k;
  1142. a = (-b1 + Math.sqrt(b1 ** 2 - 4 * a1 * c1) * ((kv > 0 && x2 > x1 || kv < 0 && x2 < x1) ? 1 : -1)) / (2 * a1);
  1143. b = k * a + l;
  1144. rSquare = (x1 - a) ** 2 + (y1 - b) ** 2;
  1145. }
  1146. if (x1 === x2 || Math.abs(kv) > 1) {
  1147. let yDistance = y2 - y1;
  1148. let yDis = yDistance / (pointCount + 1);
  1149. for (let i = 0; i < pointCount; i++) {
  1150. let y = y1 + yDis * (i + 1);
  1151. let x = Math.sqrt(rSquare - (y - b) ** 2) * (y2 > y1 ? -1 : 1) + a;
  1152. points.push([x, y]);
  1153. }
  1154. } else {
  1155. let xDistance = x2 - x1;
  1156. let xDis = xDistance / (pointCount + 1);
  1157. for (let i = 0; i < pointCount; i++) {
  1158. let x = x1 + xDis * (i + 1);
  1159. let y = Math.sqrt(rSquare - (x - a) ** 2) * (x2 > x1 ? 1 : -1) + b;
  1160. points.push([x, y]);
  1161. }
  1162. }
  1163. return points;
  1164. }
  1165. var QRCodeAlg = (function () {
  1166. function unicodeFormat8(code) { var c0, c1, c2; if (code < 128) { return [code] } else if (code < 2048) { c0 = 192 + (code >> 6); c1 = 128 + (code & 63); return [c0, c1] } else { c0 = 224 + (code >> 12); c1 = 128 + (code >> 6 & 63); c2 = 128 + (code & 63); return [c0, c1, c2] } } function getUTF8Bytes(string) { var utf8codes = []; for (var i = 0; i < string.length; i++) { var code = string.charCodeAt(i); var utf8 = unicodeFormat8(code); for (var j = 0; j < utf8.length; j++) { utf8codes.push(utf8[j]) } } return utf8codes } function QRCodeAlg(data, errorCorrectLevel) { this.typeNumber = -1; this.errorCorrectLevel = errorCorrectLevel; this.modules = null; this.moduleCount = 0; this.dataCache = null; this.rsBlocks = null; this.totalDataCount = -1; this.data = data; this.utf8bytes = getUTF8Bytes(data); this.make() } QRCodeAlg.prototype = { constructor: QRCodeAlg, getModuleCount: function () { return this.moduleCount }, make: function () { this.getRightType(); this.dataCache = this.createData(); this.createQrcode() }, makeImpl: function (maskPattern) { this.moduleCount = this.typeNumber * 4 + 17; this.modules = new Array(this.moduleCount); for (var row = 0; row < this.moduleCount; row++) { this.modules[row] = new Array(this.moduleCount) } this.setupPositionProbePattern(0, 0); this.setupPositionProbePattern(this.moduleCount - 7, 0); this.setupPositionProbePattern(0, this.moduleCount - 7); this.setupPositionAdjustPattern(); this.setupTimingPattern(); this.setupTypeInfo(true, maskPattern); if (this.typeNumber >= 7) { this.setupTypeNumber(true) } this.mapData(this.dataCache, maskPattern) }, setupPositionProbePattern: function (row, col) { for (var r = -1; r <= 7; r++) { if (row + r <= -1 || this.moduleCount <= row + r) continue; for (var c = -1; c <= 7; c++) { if (col + c <= -1 || this.moduleCount <= col + c) continue; if ((0 <= r && r <= 6 && (c == 0 || c == 6)) || (0 <= c && c <= 6 && (r == 0 || r == 6)) || (2 <= r && r <= 4 && 2 <= c && c <= 4)) { this.modules[row + r][col + c] = true } else { this.modules[row + r][col + c] = false } } } }, createQrcode: function () { var minLostPoint = 0; var pattern = 0; var bestModules = null; for (var i = 0; i < 8; i++) { this.makeImpl(i); var lostPoint = QRUtil.getLostPoint(this); if (i == 0 || minLostPoint > lostPoint) { minLostPoint = lostPoint; pattern = i; bestModules = this.modules } } this.modules = bestModules; this.setupTypeInfo(false, pattern); if (this.typeNumber >= 7) { this.setupTypeNumber(false) } }, setupTimingPattern: function () { for (var r = 8; r < this.moduleCount - 8; r++) { if (this.modules[r][6] != null) { continue } this.modules[r][6] = (r % 2 == 0); if (this.modules[6][r] != null) { continue } this.modules[6][r] = (r % 2 == 0) } }, setupPositionAdjustPattern: function () { var pos = QRUtil.getPatternPosition(this.typeNumber); for (var i = 0; i < pos.length; i++) { for (var j = 0; j < pos.length; j++) { var row = pos[i]; var col = pos[j]; if (this.modules[row][col] != null) { continue } for (var r = -2; r <= 2; r++) { for (var c = -2; c <= 2; c++) { if (r == -2 || r == 2 || c == -2 || c == 2 || (r == 0 && c == 0)) { this.modules[row + r][col + c] = true } else { this.modules[row + r][col + c] = false } } } } } }, setupTypeNumber: function (test) { var bits = QRUtil.getBCHTypeNumber(this.typeNumber); for (var i = 0; i < 18; i++) { var mod = (!test && ((bits >> i) & 1) == 1); this.modules[Math.floor(i / 3)][i % 3 + this.moduleCount - 8 - 3] = mod; this.modules[i % 3 + this.moduleCount - 8 - 3][Math.floor(i / 3)] = mod } }, setupTypeInfo: function (test, maskPattern) { var data = (QRErrorCorrectLevel[this.errorCorrectLevel] << 3) | maskPattern; var bits = QRUtil.getBCHTypeInfo(data); for (var i = 0; i < 15; i++) { var mod = (!test && ((bits >> i) & 1) == 1); if (i < 6) { this.modules[i][8] = mod } else if (i < 8) { this.modules[i + 1][8] = mod } else { this.modules[this.moduleCount - 15 + i][8] = mod } var mod = (!test && ((bits >> i) & 1) == 1); if (i < 8) { this.modules[8][this.moduleCount - i - 1] = mod } else if (i < 9) { this.modules[8][15 - i - 1 + 1] = mod } else { this.modules[8][15 - i - 1] = mod } } this.modules[this.moduleCount - 8][8] = (!test) }, createData: function () { var buffer = new QRBitBuffer(); var lengthBits = this.typeNumber > 9 ? 16 : 8; buffer.put(4, 4); buffer.put(this.utf8bytes.length, lengthBits); for (var i = 0, l = this.utf8bytes.length; i < l; i++) { buffer.put(this.utf8bytes[i], 8) } if (buffer.length + 4 <= this.totalDataCount * 8) { buffer.put(0, 4) } while (buffer.length % 8 != 0) { buffer.putBit(false) } while (true) { if (buffer.length >= this.totalDataCount * 8) { break } buffer.put(QRCodeAlg.PAD0, 8); if (buffer.length >= this.totalDataCount * 8) { break } buffer.put(QRCodeAlg.PAD1, 8) } return this.createBytes(buffer) }, createBytes: function (buffer) { var offset = 0; var maxDcCount = 0; var maxEcCount = 0; var length = this.rsBlock.length / 3; var rsBlocks = new Array(); for (var i = 0; i < length; i++) { var count = this.rsBlock[i * 3 + 0]; var totalCount = this.rsBlock[i * 3 + 1]; var dataCount = this.rsBlock[i * 3 + 2]; for (var j = 0; j < count; j++) { rsBlocks.push([dataCount, totalCount]) } } var dcdata = new Array(rsBlocks.length); var ecdata = new Array(rsBlocks.length); for (var r = 0; r < rsBlocks.length; r++) { var dcCount = rsBlocks[r][0]; var ecCount = rsBlocks[r][1] - dcCount; maxDcCount = Math.max(maxDcCount, dcCount); maxEcCount = Math.max(maxEcCount, ecCount); dcdata[r] = new Array(dcCount); for (var i = 0; i < dcdata[r].length; i++) { dcdata[r][i] = 0xff & buffer.buffer[i + offset] } offset += dcCount; var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount); var rawPoly = new QRPolynomial(dcdata[r], rsPoly.getLength() - 1); var modPoly = rawPoly.mod(rsPoly); ecdata[r] = new Array(rsPoly.getLength() - 1); for (var i = 0; i < ecdata[r].length; i++) { var modIndex = i + modPoly.getLength() - ecdata[r].length; ecdata[r][i] = (modIndex >= 0) ? modPoly.get(modIndex) : 0 } } var data = new Array(this.totalDataCount); var index = 0; for (var i = 0; i < maxDcCount; i++) { for (var r = 0; r < rsBlocks.length; r++) { if (i < dcdata[r].length) { data[index++] = dcdata[r][i] } } } for (var i = 0; i < maxEcCount; i++) { for (var r = 0; r < rsBlocks.length; r++) { if (i < ecdata[r].length) { data[index++] = ecdata[r][i] } } } return data }, mapData: function (data, maskPattern) { var inc = -1; var row = this.moduleCount - 1; var bitIndex = 7; var byteIndex = 0; for (var col = this.moduleCount - 1; col > 0; col -= 2) { if (col == 6) col--; while (true) { for (var c = 0; c < 2; c++) { if (this.modules[row][col - c] == null) { var dark = false; if (byteIndex < data.length) { dark = (((data[byteIndex] >>> bitIndex) & 1) == 1) } var mask = QRUtil.getMask(maskPattern, row, col - c); if (mask) { dark = !dark } this.modules[row][col - c] = dark; bitIndex--; if (bitIndex == -1) { byteIndex++; bitIndex = 7 } } } row += inc; if (row < 0 || this.moduleCount <= row) { row -= inc; inc = -inc; break } } } } }; QRCodeAlg.PAD0 = 0xEC; QRCodeAlg.PAD1 = 0x11; var QRErrorCorrectLevel = [1, 0, 3, 2]; var QRMaskPattern = { PATTERN000: 0, PATTERN001: 1, PATTERN010: 2, PATTERN011: 3, PATTERN100: 4, PATTERN101: 5, PATTERN110: 6, PATTERN111: 7 }; var QRUtil = { PATTERN_POSITION_TABLE: [[], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34], [6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50], [6, 30, 54], [6, 32, 58], [6, 34, 62], [6, 26, 46, 66], [6, 26, 48, 70], [6, 26, 50, 74], [6, 30, 54, 78], [6, 30, 56, 82], [6, 30, 58, 86], [6, 34, 62, 90], [6, 28, 50, 72, 94], [6, 26, 50, 74, 98], [6, 30, 54, 78, 102], [6, 28, 54, 80, 106], [6, 32, 58, 84, 110], [6, 30, 58, 86, 114], [6, 34, 62, 90, 118], [6, 26, 50, 74, 98, 122], [6, 30, 54, 78, 102, 126], [6, 26, 52, 78, 104, 130], [6, 30, 56, 82, 108, 134], [6, 34, 60, 86, 112, 138], [6, 30, 58, 86, 114, 142], [6, 34, 62, 90, 118, 146], [6, 30, 54, 78, 102, 126, 150], [6, 24, 50, 76, 102, 128, 154], [6, 28, 54, 80, 106, 132, 158], [6, 32, 58, 84, 110, 136, 162], [6, 26, 54, 82, 110, 138, 166], [6, 30, 58, 86, 114, 142, 170]], G15: (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0), G18: (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0), G15_MASK: (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1), getBCHTypeInfo: function (data) { var d = data << 10; while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) { d ^= (QRUtil.G15 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15))) } return ((data << 10) | d) ^ QRUtil.G15_MASK }, getBCHTypeNumber: function (data) { var d = data << 12; while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) { d ^= (QRUtil.G18 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18))) } return (data << 12) | d }, getBCHDigit: function (data) { var digit = 0; while (data != 0) { digit++; data >>>= 1 } return digit }, getPatternPosition: function (typeNumber) { return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1] }, getMask: function (maskPattern, i, j) { switch (maskPattern) { case QRMaskPattern.PATTERN000: return (i + j) % 2 == 0; case QRMaskPattern.PATTERN001: return i % 2 == 0; case QRMaskPattern.PATTERN010: return j % 3 == 0; case QRMaskPattern.PATTERN011: return (i + j) % 3 == 0; case QRMaskPattern.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 == 0; case QRMaskPattern.PATTERN101: return (i * j) % 2 + (i * j) % 3 == 0; case QRMaskPattern.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 == 0; case QRMaskPattern.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 == 0; default: throw new Error("bad maskPattern:" + maskPattern); } }, getErrorCorrectPolynomial: function (errorCorrectLength) { var a = new QRPolynomial([1], 0); for (var i = 0; i < errorCorrectLength; i++) { a = a.multiply(new QRPolynomial([1, QRMath.gexp(i)], 0)) } return a }, getLostPoint: function (qrCode) { var moduleCount = qrCode.getModuleCount(), lostPoint = 0, darkCount = 0; for (var row = 0; row < moduleCount; row++) { var sameCount = 0; var head = qrCode.modules[row][0]; for (var col = 0; col < moduleCount; col++) { var current = qrCode.modules[row][col]; if (col < moduleCount - 6) { if (current && !qrCode.modules[row][col + 1] && qrCode.modules[row][col + 2] && qrCode.modules[row][col + 3] && qrCode.modules[row][col + 4] && !qrCode.modules[row][col + 5] && qrCode.modules[row][col + 6]) { if (col < moduleCount - 10) { if (qrCode.modules[row][col + 7] && qrCode.modules[row][col + 8] && qrCode.modules[row][col + 9] && qrCode.modules[row][col + 10]) { lostPoint += 40 } } else if (col > 3) { if (qrCode.modules[row][col - 1] && qrCode.modules[row][col - 2] && qrCode.modules[row][col - 3] && qrCode.modules[row][col - 4]) { lostPoint += 40 } } } } if ((row < moduleCount - 1) && (col < moduleCount - 1)) { var count = 0; if (current) count++; if (qrCode.modules[row + 1][col]) count++; if (qrCode.modules[row][col + 1]) count++; if (qrCode.modules[row + 1][col + 1]) count++; if (count == 0 || count == 4) { lostPoint += 3 } } if (head ^ current) { sameCount++ } else { head = current; if (sameCount >= 5) { lostPoint += (3 + sameCount - 5) } sameCount = 1 } if (current) { darkCount++ } } } for (var col = 0; col < moduleCount; col++) { var sameCount = 0; var head = qrCode.modules[0][col]; for (var row = 0; row < moduleCount; row++) { var current = qrCode.modules[row][col]; if (row < moduleCount - 6) { if (current && !qrCode.modules[row + 1][col] && qrCode.modules[row + 2][col] && qrCode.modules[row + 3][col] && qrCode.modules[row + 4][col] && !qrCode.modules[row + 5][col] && qrCode.modules[row + 6][col]) { if (row < moduleCount - 10) { if (qrCode.modules[row + 7][col] && qrCode.modules[row + 8][col] && qrCode.modules[row + 9][col] && qrCode.modules[row + 10][col]) { lostPoint += 40 } } else if (row > 3) { if (qrCode.modules[row - 1][col] && qrCode.modules[row - 2][col] && qrCode.modules[row - 3][col] && qrCode.modules[row - 4][col]) { lostPoint += 40 } } } } if (head ^ current) { sameCount++ } else { head = current; if (sameCount >= 5) { lostPoint += (3 + sameCount - 5) } sameCount = 1 } } } var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5; lostPoint += ratio * 10; return lostPoint } }; var QRMath = { glog: function (n) { if (n < 1) { throw new Error("glog(" + n + ")"); } return QRMath.LOG_TABLE[n] }, gexp: function (n) { while (n < 0) { n += 255 } while (n >= 256) { n -= 255 } return QRMath.EXP_TABLE[n] }, EXP_TABLE: new Array(256), LOG_TABLE: new Array(256) }; for (var i = 0; i < 8; i++) { QRMath.EXP_TABLE[i] = 1 << i } for (var i = 8; i < 256; i++) { QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - 4] ^ QRMath.EXP_TABLE[i - 5] ^ QRMath.EXP_TABLE[i - 6] ^ QRMath.EXP_TABLE[i - 8] } for (var i = 0; i < 255; i++) { QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]] = i } function QRPolynomial(num, shift) { if (num.length == undefined) { throw new Error(num.length + "/" + shift); } var offset = 0; while (offset < num.length && num[offset] == 0) { offset++ } this.num = new Array(num.length - offset + shift); for (var i = 0; i < num.length - offset; i++) { this.num[i] = num[i + offset] } } QRPolynomial.prototype = { get: function (index) { return this.num[index] }, getLength: function () { return this.num.length }, multiply: function (e) { var num = new Array(this.getLength() + e.getLength() - 1); for (var i = 0; i < this.getLength(); i++) { for (var j = 0; j < e.getLength(); j++) { num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i)) + QRMath.glog(e.get(j))) } } return new QRPolynomial(num, 0) }, mod: function (e) { var tl = this.getLength(), el = e.getLength(); if (tl - el < 0) { return this } var num = new Array(tl); for (var i = 0; i < tl; i++) { num[i] = this.get(i) } while (num.length >= el) { var ratio = QRMath.glog(num[0]) - QRMath.glog(e.get(0)); for (var i = 0; i < e.getLength(); i++) { num[i] ^= QRMath.gexp(QRMath.glog(e.get(i)) + ratio) } while (num[0] == 0) { num.shift() } } return new QRPolynomial(num, 0) } }; var RS_BLOCK_TABLE = [[1, 26, 19], [1, 26, 16], [1, 26, 13], [1, 26, 9], [1, 44, 34], [1, 44, 28], [1, 44, 22], [1, 44, 16], [1, 70, 55], [1, 70, 44], [2, 35, 17], [2, 35, 13], [1, 100, 80], [2, 50, 32], [2, 50, 24], [4, 25, 9], [1, 134, 108], [2, 67, 43], [2, 33, 15, 2, 34, 16], [2, 33, 11, 2, 34, 12], [2, 86, 68], [4, 43, 27], [4, 43, 19], [4, 43, 15], [2, 98, 78], [4, 49, 31], [2, 32, 14, 4, 33, 15], [4, 39, 13, 1, 40, 14], [2, 121, 97], [2, 60, 38, 2, 61, 39], [4, 40, 18, 2, 41, 19], [4, 40, 14, 2, 41, 15], [2, 146, 116], [3, 58, 36, 2, 59, 37], [4, 36, 16, 4, 37, 17], [4, 36, 12, 4, 37, 13], [2, 86, 68, 2, 87, 69], [4, 69, 43, 1, 70, 44], [6, 43, 19, 2, 44, 20], [6, 43, 15, 2, 44, 16], [4, 101, 81], [1, 80, 50, 4, 81, 51], [4, 50, 22, 4, 51, 23], [3, 36, 12, 8, 37, 13], [2, 116, 92, 2, 117, 93], [6, 58, 36, 2, 59, 37], [4, 46, 20, 6, 47, 21], [7, 42, 14, 4, 43, 15], [4, 133, 107], [8, 59, 37, 1, 60, 38], [8, 44, 20, 4, 45, 21], [12, 33, 11, 4, 34, 12], [3, 145, 115, 1, 146, 116], [4, 64, 40, 5, 65, 41], [11, 36, 16, 5, 37, 17], [11, 36, 12, 5, 37, 13], [5, 109, 87, 1, 110, 88], [5, 65, 41, 5, 66, 42], [5, 54, 24, 7, 55, 25], [11, 36, 12], [5, 122, 98, 1, 123, 99], [7, 73, 45, 3, 74, 46], [15, 43, 19, 2, 44, 20], [3, 45, 15, 13, 46, 16], [1, 135, 107, 5, 136, 108], [10, 74, 46, 1, 75, 47], [1, 50, 22, 15, 51, 23], [2, 42, 14, 17, 43, 15], [5, 150, 120, 1, 151, 121], [9, 69, 43, 4, 70, 44], [17, 50, 22, 1, 51, 23], [2, 42, 14, 19, 43, 15], [3, 141, 113, 4, 142, 114], [3, 70, 44, 11, 71, 45], [17, 47, 21, 4, 48, 22], [9, 39, 13, 16, 40, 14], [3, 135, 107, 5, 136, 108], [3, 67, 41, 13, 68, 42], [15, 54, 24, 5, 55, 25], [15, 43, 15, 10, 44, 16], [4, 144, 116, 4, 145, 117], [17, 68, 42], [17, 50, 22, 6, 51, 23], [19, 46, 16, 6, 47, 17], [2, 139, 111, 7, 140, 112], [17, 74, 46], [7, 54, 24, 16, 55, 25], [34, 37, 13], [4, 151, 121, 5, 152, 122], [4, 75, 47, 14, 76, 48], [11, 54, 24, 14, 55, 25], [16, 45, 15, 14, 46, 16], [6, 147, 117, 4, 148, 118], [6, 73, 45, 14, 74, 46], [11, 54, 24, 16, 55, 25], [30, 46, 16, 2, 47, 17], [8, 132, 106, 4, 133, 107], [8, 75, 47, 13, 76, 48], [7, 54, 24, 22, 55, 25], [22, 45, 15, 13, 46, 16], [10, 142, 114, 2, 143, 115], [19, 74, 46, 4, 75, 47], [28, 50, 22, 6, 51, 23], [33, 46, 16, 4, 47, 17], [8, 152, 122, 4, 153, 123], [22, 73, 45, 3, 74, 46], [8, 53, 23, 26, 54, 24], [12, 45, 15, 28, 46, 16], [3, 147, 117, 10, 148, 118], [3, 73, 45, 23, 74, 46], [4, 54, 24, 31, 55, 25], [11, 45, 15, 31, 46, 16], [7, 146, 116, 7, 147, 117], [21, 73, 45, 7, 74, 46], [1, 53, 23, 37, 54, 24], [19, 45, 15, 26, 46, 16], [5, 145, 115, 10, 146, 116], [19, 75, 47, 10, 76, 48], [15, 54, 24, 25, 55, 25], [23, 45, 15, 25, 46, 16], [13, 145, 115, 3, 146, 116], [2, 74, 46, 29, 75, 47], [42, 54, 24, 1, 55, 25], [23, 45, 15, 28, 46, 16], [17, 145, 115], [10, 74, 46, 23, 75, 47], [10, 54, 24, 35, 55, 25], [19, 45, 15, 35, 46, 16], [17, 145, 115, 1, 146, 116], [14, 74, 46, 21, 75, 47], [29, 54, 24, 19, 55, 25], [11, 45, 15, 46, 46, 16], [13, 145, 115, 6, 146, 116], [14, 74, 46, 23, 75, 47], [44, 54, 24, 7, 55, 25], [59, 46, 16, 1, 47, 17], [12, 151, 121, 7, 152, 122], [12, 75, 47, 26, 76, 48], [39, 54, 24, 14, 55, 25], [22, 45, 15, 41, 46, 16], [6, 151, 121, 14, 152, 122], [6, 75, 47, 34, 76, 48], [46, 54, 24, 10, 55, 25], [2, 45, 15, 64, 46, 16], [17, 152, 122, 4, 153, 123], [29, 74, 46, 14, 75, 47], [49, 54, 24, 10, 55, 25], [24, 45, 15, 46, 46, 16], [4, 152, 122, 18, 153, 123], [13, 74, 46, 32, 75, 47], [48, 54, 24, 14, 55, 25], [42, 45, 15, 32, 46, 16], [20, 147, 117, 4, 148, 118], [40, 75, 47, 7, 76, 48], [43, 54, 24, 22, 55, 25], [10, 45, 15, 67, 46, 16], [19, 148, 118, 6, 149, 119], [18, 75, 47, 31, 76, 48], [34, 54, 24, 34, 55, 25], [20, 45, 15, 61, 46, 16]]; QRCodeAlg.prototype.getRightType = function () { for (var typeNumber = 1; typeNumber < 41; typeNumber++) { var rsBlock = RS_BLOCK_TABLE[(typeNumber - 1) * 4 + this.errorCorrectLevel]; if (rsBlock == undefined) { throw new Error("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + this.errorCorrectLevel); } var length = rsBlock.length / 3; var totalDataCount = 0; for (var i = 0; i < length; i++) { var count = rsBlock[i * 3 + 0]; var dataCount = rsBlock[i * 3 + 2]; totalDataCount += dataCount * count } var lengthBytes = typeNumber > 9 ? 2 : 1; if (this.utf8bytes.length + lengthBytes < totalDataCount || typeNumber == 40) { this.typeNumber = typeNumber; this.rsBlock = rsBlock; this.totalDataCount = totalDataCount; break } } }; function QRBitBuffer() { this.buffer = new Array(); this.length = 0 } QRBitBuffer.prototype = { get: function (index) { var bufIndex = Math.floor(index / 8); return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) }, put: function (num, length) { for (var i = 0; i < length; i++) { this.putBit(((num >>> (length - i - 1)) & 1)) } }, putBit: function (bit) { var bufIndex = Math.floor(this.length / 8); if (this.buffer.length <= bufIndex) { this.buffer.push(0) } if (bit) { this.buffer[bufIndex] |= (0x80 >>> (this.length % 8)) } this.length++ } };
  1167. return QRCodeAlg
  1168. })()
  1169. var htmlParse = (function () {
  1170. var startTag=/^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;var endTag=/^<\/([-A-Za-z0-9_]+)[^>]*>/;var attr=/([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g;var empty=makeMap('area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr');var block=makeMap('a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video');var inline=makeMap('abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var');var closeSelf=makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr');var fillAttrs=makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected');var special=makeMap('script,style');function HTMLParser(html,handler){var index;var chars;var match;var stack=[];var last=html;stack.last=function(){return this[this.length-1];};while(html){chars=true;if(!stack.last()||!special[stack.last()]){if(html.indexOf('<!--')==0){index=html.indexOf('-->');if(index>=0){if(handler.comment){handler.comment(html.substring(4,index));}
  1171. html=html.substring(index+3);chars=false;}}else if(html.indexOf('</')==0){match=html.match(endTag);if(match){html=html.substring(match[0].length);match[0].replace(endTag,parseEndTag);chars=false;}}else if(html.indexOf('<')==0){match=html.match(startTag);if(match){html=html.substring(match[0].length);match[0].replace(startTag,parseStartTag);chars=false;}}
  1172. if(chars){index=html.indexOf('<');var text=index<0?html:html.substring(0,index);html=index<0?'':html.substring(index);if(handler.chars){handler.chars(text);}}}else{html=html.replace(new RegExp('([\\s\\S]*?)<\/'+stack.last()+'[^>]*>'),function(all,text){text=text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g,'$1$2');if(handler.chars){handler.chars(text);}
  1173. return'';});parseEndTag('',stack.last());}
  1174. if(html==last){throw'Parse Error: '+html;}
  1175. last=html;}
  1176. parseEndTag();function parseStartTag(tag,tagName,rest,unary){tagName=tagName.toLowerCase();if(block[tagName]){while(stack.last()&&inline[stack.last()]){parseEndTag('',stack.last());}}
  1177. if(closeSelf[tagName]&&stack.last()==tagName){parseEndTag('',tagName);}
  1178. unary=empty[tagName]||!!unary;if(!unary){stack.push(tagName);}
  1179. if(handler.start){var attrs=[];rest.replace(attr,function(match,name){var value=arguments[2]?arguments[2]:arguments[3]?arguments[3]:arguments[4]?arguments[4]:fillAttrs[name]?name:'';attrs.push({name:name,value:value,escaped:value.replace(/(^|[^\\])"/g,'$1\\\"')});});if(handler.start){handler.start(tagName,attrs,unary);}}}
  1180. function parseEndTag(tag,tagName){if(!tagName){var pos=0;}
  1181. else{for(var pos=stack.length-1;pos>=0;pos--){if(stack[pos]==tagName){break;}}}
  1182. if(pos>=0){for(var i=stack.length-1;i>=pos;i--){if(handler.end){handler.end(stack[i]);}}
  1183. stack.length=pos;}}}
  1184. function makeMap(str){var obj={};var items=str.split(',');for(var i=0;i<items.length;i++){obj[items[i]]=true;}
  1185. return obj;}
  1186. function removeDOCTYPE(html){return html.replace(/<\?xml.*\?>\n/,'').replace(/<!doctype.*>\n/,'').replace(/<!DOCTYPE.*>\n/,'');}
  1187. function parseAttrs(attrs){return attrs.reduce(function(pre,attr){var value=attr.value;var name=attr.name;if(pre[name]){pre[name]=pre[name]+" "+value;}else{pre[name]=value;}
  1188. return pre;},{});}
  1189. function parseHtml(html){html=removeDOCTYPE(html);var stacks=[];var results={node:'root',children:[]};HTMLParser(html,{start:function start(tag,attrs,unary){var node={name:tag};if(attrs.length!==0){node.attrs=parseAttrs(attrs);}
  1190. if(unary){var parent=stacks[0]||results;if(!parent.children){parent.children=[];}
  1191. parent.children.push(node);}else{stacks.unshift(node);}},end:function end(tag){var node=stacks.shift();if(node.name!==tag)console.error('invalid state: mismatch end tag');if(stacks.length===0){results.children.push(node);}else{var parent=stacks[0];if(!parent.children){parent.children=[];}
  1192. parent.children.push(node);}},chars:function chars(text){var node={type:'text',text:text};if(stacks.length===0){results.children.push(node);}else{var parent=stacks[0];if(!parent.children){parent.children=[];}
  1193. parent.children.push(node);}},comment:function comment(text){var node={node:'comment',text:text};var parent=stacks[0];if(!parent.children){parent.children=[];}
  1194. parent.children.push(node);}});return results.children;}
  1195. return parseHtml;
  1196. })()
  1197. var imgTools = (function () {
  1198. function getLocalFilePath(path) {
  1199. if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf('_downloads') === 0) {
  1200. return path
  1201. }
  1202. if (path.indexOf('file://') === 0) {
  1203. return path
  1204. }
  1205. if (path.indexOf('/storage/emulated/0/') === 0) {
  1206. return path
  1207. }
  1208. if (path.indexOf('/') === 0) {
  1209. var localFilePath = plus.io.convertAbsoluteFileSystem(path)
  1210. if (localFilePath !== path) {
  1211. return localFilePath
  1212. } else {
  1213. path = path.substr(1)
  1214. }
  1215. }
  1216. return '_www/' + path
  1217. }
  1218. function dataUrlToBase64(str) {
  1219. var array = str.split(',')
  1220. return array[array.length - 1]
  1221. }
  1222. var index = 0
  1223. function getNewFileId() {
  1224. return Date.now() + String(index++)
  1225. }
  1226. function biggerThan(v1, v2) {
  1227. var v1Array = v1.split('.')
  1228. var v2Array = v2.split('.')
  1229. var update = false
  1230. for (var index = 0; index < v2Array.length; index++) {
  1231. var diff = v1Array[index] - v2Array[index]
  1232. if (diff !== 0) {
  1233. update = diff > 0
  1234. break
  1235. }
  1236. }
  1237. return update
  1238. }
  1239. function pathToBase64(path) {
  1240. return new Promise(function(resolve, reject) {
  1241. if (typeof window === 'object' && 'document' in window) {
  1242. if (typeof FileReader === 'function') {
  1243. var xhr = new XMLHttpRequest()
  1244. xhr.open('GET', path, true)
  1245. xhr.responseType = 'blob'
  1246. xhr.onload = function() {
  1247. if (this.status === 200) {
  1248. let fileReader = new FileReader()
  1249. fileReader.onload = function(e) {
  1250. resolve(e.target.result)
  1251. }
  1252. fileReader.onerror = reject
  1253. fileReader.readAsDataURL(this.response)
  1254. }
  1255. }
  1256. xhr.onerror = reject
  1257. xhr.send()
  1258. return
  1259. }
  1260. var canvas = document.createElement('canvas')
  1261. var c2x = canvas.getContext('2d')
  1262. var img = new Image
  1263. img.onload = function() {
  1264. canvas.width = img.width
  1265. canvas.height = img.height
  1266. c2x.drawImage(img, 0, 0)
  1267. resolve(canvas.toDataURL())
  1268. canvas.height = canvas.width = 0
  1269. }
  1270. img.onerror = reject
  1271. img.src = path
  1272. return
  1273. }
  1274. if (typeof plus === 'object') {
  1275. plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
  1276. entry.file(function(file) {
  1277. var fileReader = new plus.io.FileReader()
  1278. fileReader.onload = function(data) {
  1279. resolve(data.target.result)
  1280. }
  1281. fileReader.onerror = function(error) {
  1282. reject(error)
  1283. }
  1284. fileReader.readAsDataURL(file)
  1285. }, function(error) {
  1286. reject(error)
  1287. })
  1288. }, function(error) {
  1289. reject(error)
  1290. })
  1291. return
  1292. }
  1293. if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
  1294. wx.getFileSystemManager().readFile({
  1295. filePath: path,
  1296. encoding: 'base64',
  1297. success: function(res) {
  1298. resolve('data:image/png;base64,' + res.data)
  1299. },
  1300. fail: function(error) {
  1301. reject(error)
  1302. }
  1303. })
  1304. return
  1305. }
  1306. reject(new Error('not support'))
  1307. })
  1308. }
  1309. function base64ToPath(base64) {
  1310. return new Promise(function(resolve, reject) {
  1311. if (typeof window === 'object' && 'document' in window) {
  1312. base64 = base64.split(',')
  1313. var type = base64[0].match(/:(.*?);/)[1]
  1314. var str = atob(base64[1])
  1315. var n = str.length
  1316. var array = new Uint8Array(n)
  1317. while (n--) {
  1318. array[n] = str.charCodeAt(n)
  1319. }
  1320. return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type: type })))
  1321. }
  1322. var extName = base64.split(',')[0].match(/data\:\S+\/(\S+);/)
  1323. if (extName) {
  1324. extName = extName[1]
  1325. } else {
  1326. reject(new Error('base64 error'))
  1327. }
  1328. var fileName = getNewFileId() + '.' + extName
  1329. if (typeof plus === 'object') {
  1330. var basePath = '_doc'
  1331. var dirPath = 'uniapp_temp'
  1332. var filePath = basePath + '/' + dirPath + '/' + fileName
  1333. if (!biggerThan(plus.os.name === 'Android' ? '1.9.9.80627' : '1.9.9.80472', plus.runtime.innerVersion)) {
  1334. plus.io.resolveLocalFileSystemURL(basePath, function(entry) {
  1335. entry.getDirectory(dirPath, {
  1336. create: true,
  1337. exclusive: false,
  1338. }, function(entry) {
  1339. entry.getFile(fileName, {
  1340. create: true,
  1341. exclusive: false,
  1342. }, function(entry) {
  1343. entry.createWriter(function(writer) {
  1344. writer.onwrite = function() {
  1345. resolve(filePath)
  1346. }
  1347. writer.onerror = reject
  1348. writer.seek(0)
  1349. writer.writeAsBinary(dataUrlToBase64(base64))
  1350. }, reject)
  1351. }, reject)
  1352. }, reject)
  1353. }, reject)
  1354. return
  1355. }
  1356. var bitmap = new plus.nativeObj.Bitmap(fileName)
  1357. bitmap.loadBase64Data(base64, function() {
  1358. bitmap.save(filePath, {}, function() {
  1359. bitmap.clear()
  1360. resolve(filePath)
  1361. }, function(error) {
  1362. bitmap.clear()
  1363. reject(error)
  1364. })
  1365. }, function(error) {
  1366. bitmap.clear()
  1367. reject(error)
  1368. })
  1369. return
  1370. }
  1371. function getEnvPath() {
  1372. if(typeof my === 'object' && my?.env?.USER_DATA_PATH) {
  1373. // console.log('my')
  1374. return my.env.USER_DATA_PATH
  1375. }
  1376. if(typeof swan === 'object' && swan?.env?.USER_DATA_PATH) {
  1377. // console.log('swan')
  1378. return swan.env.USER_DATA_PATH
  1379. }
  1380. if(typeof tt === 'object' && tt?.env?.USER_DATA_PATH) {
  1381. // console.log('tt')
  1382. return tt.env.USER_DATA_PATH
  1383. }
  1384. if(typeof qq === 'object' && qq?.env?.USER_DATA_PATH) {
  1385. // console.log('qq')
  1386. return qq.env.USER_DATA_PATH
  1387. }
  1388. if(typeof qh === 'object' && qh?.env?.USER_DATA_PATH) {
  1389. // console.log('qh')
  1390. return qh.env.USER_DATA_PATH
  1391. }
  1392. if(typeof wx === 'object' && wx?.env?.USER_DATA_PATH) {
  1393. // console.log('wx')
  1394. return wx.env.USER_DATA_PATH
  1395. }
  1396. return 'https://user'
  1397. }
  1398. try{
  1399. var filePath = getEnvPath() + '/' + fileName
  1400. uni.getFileSystemManager().writeFile({
  1401. filePath: filePath,
  1402. data: dataUrlToBase64(base64),
  1403. encoding: 'base64',
  1404. success: function() {
  1405. resolve(filePath)
  1406. },
  1407. fail: function(error) {
  1408. reject(error)
  1409. }
  1410. })
  1411. }catch(e){
  1412. //TODO handle the exception
  1413. reject(new Error('not support'))
  1414. }
  1415. })
  1416. }
  1417. return {pathToBase64, base64ToPath}
  1418. })()
  1419. if (notUnd(typeof module)) {
  1420. module.exports = QSCanvas
  1421. }
  1422. return QSCanvas
  1423. })();