Add ellipses to overflowing text in SVG?

前端 未结 6 1062
广开言路
广开言路 2020-11-30 03:20

I\'m using D3.js. I\'d like to find an SVG equivalent to this CSS class, which adds ellipses if text flows out of its containing div:



        
6条回答
  •  佛祖请我去吃肉
    2020-11-30 03:56

    Just an update on the wrap function proposed by user2846569. getComputedTextLength() tends to be really slow, so...

    EDIT

    I diligently applied the advice by user2846569 and made a version with "binary" search, with some calibration and parametrized precision.

    'use strict';
    
    var width = 2560;
    
    d3.select('svg').attr('width', width);
    
    // From http://stackoverflow.com/questions/10726909/random-alpha-numeric-string-in-javascript
    function randomString(length, chars) {
        var result = '';
        for (var i = length; i > 0; --i)
            result += chars[Math.floor(Math.random() * chars.length)];
        return result;
    }
    
    function wrap() {
        var self = d3.select(this),
            textWidth = self.node().getComputedTextLength(),    // Width of text in pixel.
            initialText = self.text(),                          // Initial text.
            textLength = initialText.length,                    // Length of text in characters.
            text = initialText,
            precision = 10, //textWidth / width,                // Adjustable precision.
            maxIterations = 100; // width;                      // Set iterations limit.
    
        while (maxIterations > 0 && text.length > 0 && Math.abs(width - textWidth) > precision) {
    
            text = /*text.slice(0,-1); =*/(textWidth >= width) ? text.slice(0, -textLength * 0.15) : initialText.slice(0, textLength * 1.15);
            self.text(text + '...');
            textWidth = self.node().getComputedTextLength();
            textLength = text.length;
            maxIterations--;
        }
        console.log(width - textWidth);
    }
    
    var g = d3.select('g');
    
    g.append('text').append('tspan').text(function(d) {
        return randomString(width, 'a');
    }).each(wrap);
    

    View on JSFiddle.

提交回复
热议问题