Skip to content

feat: new setPlatformAPI method#840

Merged
pissang merged 8 commits intonextfrom
svg-ssr
Oct 15, 2021
Merged

feat: new setPlatformAPI method#840
pissang merged 8 commits intonextfrom
svg-ssr

Conversation

@pissang
Copy link
Contributor

@pissang pissang commented Oct 15, 2021

This feature introduces new setPlatformAPI method to provide the ability to extend platform-dependent methods.

When we using SSR mode in #836. There is still an issue that hasn't been solved. If we use a customized font, which glyph is very different from the default font. There is no built-in method for NodeJS or echarts to get text width accurately. In this case, we still need to rely on the third-party library like node-canvas to measure text. The original method zrender.util.$override('createCanvas', () => ...) looks very internal.

So in this PR we abstract a new concept platform that can provide these platform-dependent methods. Currently there are three methods.

createCanvas

createCanvas() => HTMLCanvasElement

Same with the original zrender.util.createCanvas. With this, you can use node-canvas or some other canvas like API in NodeJS.

const { createCanvas } = require('canvas')
zrender.setPlatformAPI({
  createCanvas() {
     return createCanvas(200, 200);
  }
});

measureText.

measureText(text: string, font: string) => {width: number}

If you have a more lightweight text measurement implementation. You can only extend this method. It's not required if you have registered createCanvas and canvas implementation already have measureText method.

loadImage

loadImage(src: string, onload: () => void, onerror: () => void): HTMLImageElement

If you are using node-canvas or some other canvas like API and wan't draw images. This will be required.

const { createCanvas, Image } = require('canvas')
zrender.setPlatformAPI({
  createCanvas() {
     return createCanvas(200, 200);
  },
  loadImage(src, onload, onerror) {
      const image = new Image();
      image.onload = onload;
      image.onerror = onerror;
      image.src = src;
      return image;
  }
});

Or in SSR mode. Only image width/height is needed. We can provide a more lightweight method.

var getImageSize = require('image-size');
zrender.setPlatformAPI({
  createCanvas() {
     return createCanvas(200, 200);
  },
  loadImage(src, onload, onerror) {
      var dimensions = getImageSize(src);
      // Only width and height are necessary in SSR mode. Also because it's sync, there is no need to call onload or onerror
       return { width: dimensions.width, height: dimensions.height };
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

Comments