canvas.js 8.1 KB

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