UNPKG

@domoinc/multiline-chart

Version:

MultiLineChart - Domo Widget

95 lines (82 loc) 3.11 kB
//********************************************************************************** // This function will determine the font size for a string given the amount of // room available to show it. // textElement: the selection of the text. // returns: font-size (i.e. "14px" - "0px") // Example: // bubblesGroup.append("text").attr("class", "bubbleTitle") // .attr("fill", "black") // .text("Hey you!") // .attr("font-size", function (d) // { // return d3.DomoGetFontSizeToFitTextInBounds(d3.select(this), 10, 10); // }) // . // . // //********************************************************************************** // d3.DomoGetFontSizeToFitTextInBounds = function(textElement, width, height) // { // var possibleTextSizes = ["14px", "12px", "10px", "8px", "0px"]; // var pTextIndex = 0; // var padding = 5; // var tempBox = null; // while (pTextIndex != possibleTextSizes.length - 1) // { // //Try a font size // textElement.attr("font-size", possibleTextSizes[pTextIndex]); // tempBox = textElement.node().getBBox(); // //Check if it fits // if (tempBox.width < width - padding && // tempBox.height < height - padding) // break; //Got it // else // pTextIndex++; //Try the next smaller size. // } // return possibleTextSizes[pTextIndex]; // }; // this edit makes it possible to have a 0px size returned, and allows you to pass a starting // size e.g. startingSize = "10px" will return text at 10px or smaller. d3.DomoGetFontSizeToFitTextInBounds = function(textElement, width, height, startingSize) { var possibleTextSizes = ["14px", "10px", "8px", "0.1px"]; var pTextIndex = possibleTextSizes.indexOf( startingSize ) || 0; var padding = 5; var tempBox = null; while (pTextIndex < possibleTextSizes.length) { //Try a font size textElement.style("font-size", possibleTextSizes[pTextIndex]); tempBox = textElement.node().getBBox(); //Check if it fits if (tempBox.width < width - padding && tempBox.height < height - padding) break; //Got it else pTextIndex++; //Try the next smaller size. } return possibleTextSizes[pTextIndex]; }; //********************************************************************************** // Same as above but let you pick the start size. // It will start as the passed in size and decrement that size by 2 until // the text fits in the passed in width and height minus a small amount of padding. //********************************************************************************** d3.DomoGetFontSizeToFitTextInBoundsStartAtSize = function(textElement, width, height, size) { var padding = 5; var tempBox = null; while (size > 0) { //Try a font size textElement.style("font-size", size + "px"); tempBox = textElement.node().getBBox(); //Check if it fits if (tempBox.width < width - padding && tempBox.height < height - padding) break; //Got it else size = size - 2; //Try the next smaller size. } return (size < 0 ? 0 : size); };