canvas.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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) {this._initStyle(ctx)}
  128. this._initEvent();
  129. this._ee = new EventEmit()
  130. }
  131. getContext(type) {
  132. if (type === '2d') {
  133. return this.ctx;
  134. }
  135. }
  136. setAttribute(key, value) {
  137. if(key === 'aria-label') {
  138. this.com['ariaLabel'] = value
  139. }
  140. }
  141. setChart(chart) {
  142. this.chart = chart;
  143. }
  144. createOffscreenCanvas(param){
  145. if(!this.children) {
  146. this.com.isOffscreenCanvas = true
  147. this.com.offscreenWidth = param.width||300
  148. this.com.offscreenHeight = param.height||300
  149. const com = this.com
  150. const canvasId = this.com.offscreenCanvasId
  151. const context = uni.createCanvasContext(canvasId, this.com)
  152. this._initStyle(context)
  153. this.children = new OffscreenCanvas(context, com, canvasId)
  154. }
  155. return this.children
  156. }
  157. appendChild(child) {
  158. console.log('child', child)
  159. }
  160. dispatchEvent(type, e) {
  161. if(typeof type == 'object') {
  162. this._ee.emit(type.type, type);
  163. } else {
  164. this._ee.emit(type, e);
  165. }
  166. return true
  167. }
  168. attachEvent() {
  169. }
  170. detachEvent() {
  171. }
  172. addEventListener(type, listener) {
  173. this._ee.on(type, listener)
  174. }
  175. removeEventListener(type, listener) {
  176. this._ee.off(type, listener)
  177. }
  178. _initCanvas(zrender, ctx) {
  179. zrender.util.getContext = function() {
  180. return ctx;
  181. };
  182. zrender.util.$override('measureText', function(text, font) {
  183. ctx.font = font || '12px sans-serif';
  184. return ctx.measureText(text, font);
  185. });
  186. }
  187. _initStyle(ctx, child) {
  188. const styles = [
  189. 'fillStyle',
  190. 'strokeStyle',
  191. 'fontSize',
  192. 'globalAlpha',
  193. 'opacity',
  194. 'textAlign',
  195. 'textBaseline',
  196. 'shadow',
  197. 'lineWidth',
  198. 'lineCap',
  199. 'lineJoin',
  200. 'lineDash',
  201. 'miterLimit',
  202. 'font'
  203. ];
  204. const colorReg = /#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])\b/g;
  205. styles.forEach(style => {
  206. Object.defineProperty(ctx, style, {
  207. set: value => {
  208. if (style === 'font' && fontSizeReg.test(value)) {
  209. const match = fontSizeReg.exec(value);
  210. ctx.setFontSize(match[1]);
  211. return;
  212. }
  213. if (style === 'opacity') {
  214. ctx.setGlobalAlpha(value)
  215. return;
  216. }
  217. if (style !== 'fillStyle' && style !== 'strokeStyle' || value !== 'none' && value !== null) {
  218. // #ifdef H5 || APP-PLUS || MP-BAIDU
  219. if(typeof value == 'object') {
  220. if (value.hasOwnProperty('colorStop') || value.hasOwnProperty('colors')) {
  221. ctx['set' + style.charAt(0).toUpperCase() + style.slice(1)](value);
  222. }
  223. return
  224. }
  225. // #endif
  226. // #ifdef MP-TOUTIAO
  227. if(colorReg.test(value)) {
  228. value = value.replace(colorReg, '#$1$1$2$2$3$3')
  229. }
  230. // #endif
  231. ctx['set' + style.charAt(0).toUpperCase() + style.slice(1)](value);
  232. }
  233. }
  234. });
  235. });
  236. if(!this.isNew && !child) {
  237. ctx.uniDrawImage = ctx.drawImage
  238. ctx.drawImage = (...a) => {
  239. a[0] = a[0].src
  240. ctx.uniDrawImage(...a)
  241. }
  242. }
  243. if(!ctx.createRadialGradient) {
  244. ctx.createRadialGradient = function() {
  245. return ctx.createCircularGradient(...[...arguments].slice(-3))
  246. };
  247. }
  248. // 字节不支持
  249. if (!ctx.strokeText) {
  250. ctx.strokeText = (...a) => {
  251. ctx.fillText(...a)
  252. }
  253. }
  254. // 钉钉不支持
  255. if (!ctx.measureText) {
  256. const strLen = (str) => {
  257. let len = 0;
  258. for (let i = 0; i < str.length; i++) {
  259. if (str.charCodeAt(i) > 0 && str.charCodeAt(i) < 128) {
  260. len++;
  261. } else {
  262. len += 2;
  263. }
  264. }
  265. return len;
  266. }
  267. ctx.measureText = (text, font) => {
  268. let fontSize = 12;
  269. if (font) {
  270. fontSize = parseInt(font.match(/([\d\.]+)px/)[1])
  271. }
  272. fontSize /= 2;
  273. return {
  274. width: strLen(text) * fontSize
  275. };
  276. }
  277. }
  278. }
  279. _initEvent(e) {
  280. this.event = {};
  281. const eventNames = [{
  282. wxName: 'touchStart',
  283. ecName: 'mousedown'
  284. }, {
  285. wxName: 'touchMove',
  286. ecName: 'mousemove'
  287. }, {
  288. wxName: 'touchEnd',
  289. ecName: 'mouseup'
  290. }, {
  291. wxName: 'touchEnd',
  292. ecName: 'click'
  293. }];
  294. eventNames.forEach(name => {
  295. this.event[name.wxName] = e => {
  296. const touch = e.touches[0];
  297. this.chart.getZr().handler.dispatch(name.ecName, {
  298. zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
  299. zrY: name.wxName === 'tap' ? touch.clientY : touch.y
  300. });
  301. };
  302. });
  303. }
  304. set width(w) {
  305. this.canvasNode.width = w
  306. }
  307. set height(h) {
  308. this.canvasNode.height = h
  309. }
  310. get width() {
  311. return this.canvasNode.width || 0
  312. }
  313. get height() {
  314. return this.canvasNode.height || 0
  315. }
  316. get ctx() {
  317. return cacheChart[this.canvasId]['ctx'] || null
  318. }
  319. set chart(chart) {
  320. cacheChart[this.canvasId]['chart'] = chart
  321. }
  322. get chart() {
  323. return cacheChart[this.canvasId]['chart'] || null
  324. }
  325. }
  326. export function dispatch(name, {x,y, wheelDelta}) {
  327. this.dispatch(name, {
  328. zrX: x,
  329. zrY: y,
  330. zrDelta: wheelDelta,
  331. preventDefault: () => {},
  332. stopPropagation: () =>{}
  333. });
  334. }
  335. export function setCanvasCreator(echarts, {canvas, node}) {
  336. // echarts.setCanvasCreator(() => canvas);
  337. if(echarts && !echarts.registerPreprocessor) {
  338. return console.warn('echarts 版本不对或未传入echarts,vue3请使用esm格式')
  339. }
  340. echarts.registerPreprocessor(option => {
  341. if (option && option.series) {
  342. if (option.series.length > 0) {
  343. option.series.forEach(series => {
  344. series.progressive = 0;
  345. });
  346. } else if (typeof option.series === 'object') {
  347. option.series.progressive = 0;
  348. }
  349. }
  350. });
  351. function loadImage(src, onload, onerror) {
  352. let img = null
  353. if(node && node.createImage) {
  354. img = node.createImage()
  355. img.onload = onload.bind(img);
  356. img.onerror = onerror.bind(img);
  357. img.src = src;
  358. return img
  359. } else {
  360. img = new Image()
  361. img.onload = onload.bind(img)
  362. img.onerror = onerror.bind(img);
  363. img.src = src
  364. return img
  365. }
  366. }
  367. if(echarts.setPlatformAPI) {
  368. echarts.setPlatformAPI({
  369. loadImage: canvas.setChart ? loadImage : null,
  370. createCanvas(){
  371. return canvas
  372. }
  373. })
  374. }
  375. }