use computeWidthOfText

This commit is contained in:
Issue哥 2023-07-07 15:42:40 +08:00
parent f211ed686c
commit a2d1fb5e54
3 changed files with 7 additions and 12 deletions

View File

@ -4,7 +4,7 @@ import { log } from '../../logger.js';
import { configureSvgSize } from '../../setupGraphViewbox.js';
import * as configApi from '../../config.js';
import { parseFontSize } from '../../utils.js';
import { getTextWidth } from '../../rendering-util/getTextWidth.js';
import { computeWidthOfText } from '../../rendering-util/createText.js';
let conf = configApi.getConfig();
@ -74,16 +74,18 @@ export const draw = (txt, id, _version, diagObj) => {
sum += data[key];
});
const legendShowData = diagObj.db.getShowData() || conf.showData || conf.pie.showData || false;
const legendShowData = diagObj.db.getShowData();
const legendTexts = Object.keys(data).map(key => {
if (!legendShowData) {
return key;
}
return `${key} [${data[key]}]`;
})
const longestTextWidth = Math.max(...(legendTexts.map(v => getTextWidth(v))));
const longestTextWidth = Math.max(...(legendTexts.map(text => {
return computeWidthOfText(svg, 1, text)
})));
const newWidth = width + margin + legendRectSize + legendSpacing + longestTextWidth;
elem.setAttribute("viewBox", "0 0 " + newWidth + " " + height);
elem.setAttribute("viewBox", `0 0 ${newWidth} ${height}`);
const themeVariables = conf.themeVariables;
var myGeneratedColors = [

View File

@ -85,7 +85,7 @@ function createTspan(textElement, lineIndex, lineHeight) {
* @param {string} text
* @returns {number}
*/
function computeWidthOfText(parentNode, lineHeight, text) {
export function computeWidthOfText(parentNode, lineHeight, text) {
const testElement = parentNode.append('text');
const testSpan = createTspan(testElement, 1, lineHeight);
updateTextContentAndStyles(testSpan, [{ content: text, type: 'normal' }]);

View File

@ -1,7 +0,0 @@
// https://stackoverflow.com/a/35373030/3469145
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const getTextWidth = (text) => context.measureText(text).width * window.devicePixelRatio;
export { getTextWidth };