canvas.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. const cacheChart = {}
  2. const fontSizeReg = /([\d\.]+)px/;
  3. class EventEmit {
  4. constructor() {
  5. this.__events = {};
  6. }
  7. on(type, listener) {
  8. if (!type || !listener) {
  9. return;
  10. }
  11. const events = this.__events[type] || [];
  12. events.push(listener);
  13. this.__events[type] = events;
  14. }
  15. emit(type, e) {
  16. if (type.constructor === Object) {
  17. e = type;
  18. type = e && e.type;
  19. }
  20. if (!type) {
  21. return;
  22. }
  23. const events = this.__events[type];
  24. if (!events || !events.length) {
  25. return;
  26. }
  27. events.forEach((listener) => {
  28. listener.call(this, e);
  29. });
  30. }
  31. off(type, listener) {
  32. const __events = this.__events;
  33. const events = __events[type];
  34. if (!events || !events.length) {
  35. return;
  36. }
  37. if (!listener) {
  38. delete __events[type];
  39. return;
  40. }
  41. for (let i = 0, len = events.length; i < len; i++) {
  42. if (events[i] === listener) {
  43. events.splice(i, 1);
  44. i--;
  45. }
  46. }
  47. }
  48. }
  49. class Image {
  50. constructor() {
  51. this.currentSrc = null
  52. this.naturalHeight = 0
  53. this.naturalWidth = 0
  54. this.width = 0
  55. this.height = 0
  56. this.tagName = 'IMG'
  57. }
  58. set src(src) {
  59. this.currentSrc = src
  60. uni.getImageInfo({
  61. src,
  62. success: (res) => {
  63. this.naturalWidth = this.width = res.width
  64. this.naturalHeight = this.height = res.height
  65. this.onload()
  66. },
  67. fail: () => {
  68. this.onerror()
  69. }
  70. })
  71. }
  72. get src() {
  73. return this.currentSrc
  74. }
  75. }
  76. class OffscreenCanvas {
  77. constructor(ctx, com, canvasId) {
  78. this.tagName = 'canvas'
  79. this.com = com
  80. this.canvasId = canvasId
  81. this.ctx = ctx
  82. }
  83. set width(w) {
  84. this.com.offscreenWidth = w
  85. }
  86. set height(h) {
  87. this.com.offscreenHeight = h
  88. }
  89. get width() {
  90. return this.com.offscreenWidth || 0
  91. }
  92. get height() {
  93. return this.com.offscreenHeight || 0
  94. }
  95. getContext(type) {
  96. return this.ctx
  97. }
  98. getImageData() {
  99. return new Promise((resolve, reject) => {
  100. this.com.$nextTick(() => {
  101. uni.canvasGetImageData({
  102. x:0,
  103. y:0,
  104. width: this.com.offscreenWidth,
  105. height: this.com.offscreenHeight,
  106. canvasId: this.canvasId,
  107. success: (res) => {
  108. resolve(res)
  109. },
  110. fail: (err) => {
  111. reject(err)
  112. },
  113. }, this.com)
  114. })
  115. })
  116. }
  117. }
  118. export class Canvas {
  119. constructor(ctx, com, isNew, canvasNode={}) {
  120. cacheChart[com.canvasId] = {ctx}
  121. this.canvasId = com.canvasId;
  122. this.chart = null;
  123. this.isNew = isNew
  124. this.tagName = 'canvas'
  125. this.canvasNode = canvasNode;
  126. this.com = com;
  127. if (!isNew) {
  128. this._initStyle(ctx)
  129. }
  130. this._initEvent();
  131. this._ee = new EventEmit()
  132. }
  133. getContext(type) {
  134. if (type === '2d') {
  135. return this.ctx;
  136. }
  137. }
  138. setAttribute(key, value) {
  139. if(key === 'aria-label') {
  140. this.com['ariaLabel'] = value
  141. }
  142. }
  143. setChart(chart) {
  144. this.chart = chart;
  145. }
  146. createOffscreenCanvas(param){
  147. if(!this.children) {
  148. this.com.isOffscreenCanvas = true
  149. this.com.offscreenWidth = param.width||300
  150. this.com.offscreenHeight = param.height||300
  151. const com = this.com
  152. const canvasId = this.com.offscreenCanvasId
  153. const context = uni.createCanvasContext(canvasId, this.com)
  154. this._initStyle(context)
  155. this.children = new OffscreenCanvas(context, com, canvasId)
  156. }
  157. return this.children
  158. }
  159. appendChild(child) {
  160. console.log('child', child)
  161. }
  162. dispatchEvent(type, e) {
  163. if(typeof type == 'object') {
  164. this._ee.emit(type.type, type);
  165. } else {
  166. this._ee.emit(type, e);
  167. }
  168. return true
  169. }
  170. attachEvent() {
  171. }
  172. detachEvent() {
  173. }
  174. addEventListener(type, listener) {
  175. this._ee.on(type, listener)
  176. }
  177. removeEventListener(type, listener) {
  178. this._ee.off(type, listener)
  179. }
  180. _initCanvas(zrender, ctx) {
  181. // zrender.util.getContext = function() {
  182. // return ctx;
  183. // };
  184. // zrender.util.$override('measureText', function(text, font) {
  185. // ctx.font = font || '12px sans-serif';
  186. // return ctx.measureText(text, font);
  187. // });
  188. }
  189. _initStyle(ctx, child) {
  190. const styles = [
  191. 'fillStyle',
  192. 'strokeStyle',
  193. 'fontSize',
  194. 'globalAlpha',
  195. 'opacity',
  196. 'textAlign',
  197. 'textBaseline',
  198. 'shadow',
  199. 'lineWidth',
  200. 'lineCap',
  201. 'lineJoin',
  202. 'lineDash',
  203. 'miterLimit',
  204. // 'font'
  205. ];
  206. const colorReg = /#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])\b/g;
  207. styles.forEach(style => {
  208. Object.defineProperty(ctx, style, {
  209. set: value => {
  210. // if (style === 'font' && fontSizeReg.test(value)) {
  211. // const match = fontSizeReg.exec(value);
  212. // ctx.setFontSize(match[1]);
  213. // return;
  214. // }
  215. if (style === 'opacity') {
  216. ctx.setGlobalAlpha(value)
  217. return;
  218. }
  219. if (style !== 'fillStyle' && style !== 'strokeStyle' || value !== 'none' && value !== null) {
  220. // #ifdef H5 || APP-PLUS || MP-BAIDU
  221. if(typeof value == 'object') {
  222. if (value.hasOwnProperty('colorStop') || value.hasOwnProperty('colors')) {
  223. ctx['set' + style.charAt(0).toUpperCase() + style.slice(1)](value);
  224. }
  225. return
  226. }
  227. // #endif
  228. // #ifdef MP-TOUTIAO
  229. if(colorReg.test(value)) {
  230. value = value.replace(colorReg, '#$1$1$2$2$3$3')
  231. }
  232. // #endif
  233. ctx['set' + style.charAt(0).toUpperCase() + style.slice(1)](value);
  234. }
  235. }
  236. });
  237. });
  238. if(!this.isNew && !child) {
  239. ctx.uniDrawImage = ctx.drawImage
  240. ctx.drawImage = (...a) => {
  241. a[0] = a[0].src
  242. ctx.uniDrawImage(...a)
  243. }
  244. }
  245. if(!ctx.createRadialGradient) {
  246. ctx.createRadialGradient = function() {
  247. return ctx.createCircularGradient(...[...arguments].slice(-3))
  248. };
  249. }
  250. // 字节不支持
  251. if (!ctx.strokeText) {
  252. ctx.strokeText = (...a) => {
  253. ctx.fillText(...a)
  254. }
  255. }
  256. // 钉钉不支持
  257. if (!ctx.measureText) {
  258. const strLen = (str) => {
  259. let len = 0;
  260. for (let i = 0; i < str.length; i++) {
  261. if (str.charCodeAt(i) > 0 && str.charCodeAt(i) < 128) {
  262. len++;
  263. } else {
  264. len += 2;
  265. }
  266. }
  267. return len;
  268. }
  269. ctx.measureText = (text, font) => {
  270. let fontSize = ctx?.state?.fontSize || 12;
  271. if (font) {
  272. fontSize = parseInt(font.match(/([\d\.]+)px/)[1])
  273. }
  274. fontSize /= 2;
  275. let isBold = fontSize >= 16;
  276. const widthFactor = isBold ? 1.3 : 1;
  277. return {
  278. width: strLen(text) * fontSize * widthFactor
  279. };
  280. }
  281. }
  282. }
  283. _initEvent(e) {
  284. this.event = {};
  285. const eventNames = [{
  286. wxName: 'touchStart',
  287. ecName: 'mousedown'
  288. }, {
  289. wxName: 'touchMove',
  290. ecName: 'mousemove'
  291. }, {
  292. wxName: 'touchEnd',
  293. ecName: 'mouseup'
  294. }, {
  295. wxName: 'touchEnd',
  296. ecName: 'click'
  297. }];
  298. eventNames.forEach(name => {
  299. this.event[name.wxName] = e => {
  300. const touch = e.touches[0];
  301. this.chart.getZr().handler.dispatch(name.ecName, {
  302. zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
  303. zrY: name.wxName === 'tap' ? touch.clientY : touch.y
  304. });
  305. };
  306. });
  307. }
  308. set width(w) {
  309. this.canvasNode.width = w
  310. }
  311. set height(h) {
  312. this.canvasNode.height = h
  313. }
  314. get width() {
  315. return this.canvasNode.width || 0
  316. }
  317. get height() {
  318. return this.canvasNode.height || 0
  319. }
  320. get ctx() {
  321. return cacheChart[this.canvasId]['ctx'] || null
  322. }
  323. set chart(chart) {
  324. cacheChart[this.canvasId]['chart'] = chart
  325. }
  326. get chart() {
  327. return cacheChart[this.canvasId]['chart'] || null
  328. }
  329. }
  330. export function dispatch(name, {x,y, wheelDelta}) {
  331. this.dispatch(name, {
  332. zrX: x,
  333. zrY: y,
  334. zrDelta: wheelDelta,
  335. preventDefault: () => {},
  336. stopPropagation: () =>{}
  337. });
  338. }
  339. export function setCanvasCreator(echarts, {canvas, node}) {
  340. // echarts.setCanvasCreator(() => canvas);
  341. if(echarts && !echarts.registerPreprocessor) {
  342. return console.warn('echarts 版本不对或未传入echarts,vue3请使用esm格式')
  343. }
  344. echarts.registerPreprocessor(option => {
  345. if (option && option.series) {
  346. if (option.series.length > 0) {
  347. option.series.forEach(series => {
  348. series.progressive = 0;
  349. });
  350. } else if (typeof option.series === 'object') {
  351. option.series.progressive = 0;
  352. }
  353. }
  354. });
  355. function loadImage(src, onload, onerror) {
  356. let img = null
  357. if(node && node.createImage) {
  358. img = node.createImage()
  359. img.onload = onload.bind(img);
  360. img.onerror = onerror.bind(img);
  361. img.src = src;
  362. return img
  363. } else {
  364. img = new Image()
  365. img.onload = onload.bind(img)
  366. img.onerror = onerror.bind(img);
  367. img.src = src
  368. return img
  369. }
  370. }
  371. if(echarts.setPlatformAPI) {
  372. echarts.setPlatformAPI({
  373. loadImage: canvas.setChart ? loadImage : null,
  374. createCanvas(){
  375. const key = 'createOffscreenCanvas'
  376. return uni.canIUse(key) && uni[key] ? uni[key]({type: '2d'}) : canvas
  377. }
  378. })
  379. }
  380. }