canvas.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import GContext2D from '../context-2d/RenderingContext';
  2. import GContextWebGL from '../context-webgl/RenderingContext';
  3. export default class GCanvas {
  4. // static GBridge = null;
  5. id = null;
  6. _needRender = true;
  7. constructor(id, { disableAutoSwap }) {
  8. this.id = id;
  9. this._disableAutoSwap = disableAutoSwap;
  10. if (disableAutoSwap) {
  11. this._swapBuffers = () => {
  12. GCanvas.GBridge.render(this.id);
  13. }
  14. }
  15. }
  16. getContext(type) {
  17. let context = null;
  18. if (type.match(/webgl/i)) {
  19. context = new GContextWebGL(this);
  20. context.componentId = this.id;
  21. if (!this._disableAutoSwap) {
  22. const render = () => {
  23. if (this._needRender) {
  24. GCanvas.GBridge.render(this.id);
  25. this._needRender = false;
  26. }
  27. }
  28. setInterval(render, 16);
  29. }
  30. GCanvas.GBridge.callSetContextType(this.id, 1); // 0 for 2d; 1 for webgl
  31. } else if (type.match(/2d/i)) {
  32. context = new GContext2D(this);
  33. context.componentId = this.id;
  34. // const render = ( callback ) => {
  35. //
  36. // const commands = context._drawCommands;
  37. // context._drawCommands = '';
  38. //
  39. // GCanvas.GBridge.render2d(this.id, commands, callback);
  40. // this._needRender = false;
  41. // }
  42. // //draw方法触发
  43. // context._flush = render;
  44. // //setInterval(render, 16);
  45. GCanvas.GBridge.callSetContextType(this.id, 0);
  46. } else {
  47. throw new Error('not supported context ' + type);
  48. }
  49. return context;
  50. }
  51. reset() {
  52. GCanvas.GBridge.callReset(this.id);
  53. }
  54. }