简体   繁体   English

使用SVG和d3.js创建滚动条

[英]Creating scrollbars with SVG and d3.js

Right now I've used d3 to create several "boxes" that are merely SVG rectangles with text: 现在我用d3创建了几个“盒子”,它们只是带有文本的SVG矩形:

var canvas = d3.select("body").append("svg")
    .attr("width", 800)
    .attr("height", 500);


//specifies drawing area for each box
var boxes = canvas.selectAll("rect")
    .data(classData)
    .enter();

boxes.append("rect")
        .attr("width", boxWidth)
        .attr("height", boxHeight)
        .attr("fill", boxColor)
        .attr("x", function (d, i) { return i * 2 * boxWidth });


text.append("text")
        .attr("fill", textColor)
        .attr("x", function (d, i) 
              { return i * 2 * boxWidth + 5 })
        .attr("y", 20)
        .style("width", "20px")
        .style("overflow-x", "scroll")
        .text(function(d) {return d.name});

在此输入图像描述

Now what I'd like to do is add scrollbars to each box when the text is outside the bounds of the box. 现在我想要做的是当文本超出框的边界时向每个框添加滚动条。 I've seen a couple examples that created a div and used CSS to handle the overflow. 我见过几个创建div示例,并使用CSS来处理溢出。 However, I will have multiple (variable) boxes and I'm not sure how to go about this. 但是,我将有多个(可变)盒子,我不知道该怎么做。

Any suggestions? 有什么建议么?

-- UPDATE -- - 更新 -

I was able to get scrollbars to appear by appending svg elements to a div that controls scrolling with CSS styles. 通过将svg元素附加到控制使用CSS样式滚动的div,我能够显示滚动条。

.container {
    height: 225px;
    width: 175px;
    border:2px solid #000;
    overflow-y: scroll;
    overflow-x: hidden;
}

svg {
    display: block;
    width: 200%;
    height: 200%;
}

However, the scrolling seems to be affected only by the width and height percentages of the svg element rather than the rect element that is drawn in the div. 但是,滚动似乎只受svg元素的宽度和高度百分比的影响,而不是div中绘制的rect元素。 In other words, if the rectangle is too large, you still can not scroll to see all of it, unless you increase the width and height of the svg element. 换句话说,如果矩形太大,除非增加svg元素的宽度和高度,否则仍然无法滚动查看所有矩形。

Is there a way I can have the div scroll based on what is drawn inside of it? 有没有一种方法可以根据内部绘制的内容进行div滚动? Or should I try to somehow calculate and change the width and height attributes of the svg element? 或者我应该尝试以某种方式计算和更改svg元素的宽度和高度属性?

view the code here 在这里查看代码

Try to add the viewBox svg property: 尝试添加viewBox svg属性:

var rectangle = container.append("svg")
    .attr("viewBox", "0,0,150,420")
    .append("rect")
    .attr("width", 150)
    .attr("height", 420)
    .attr("fill", "steelblue")
    .attr("x", 0)
    .attr("y", 0);

jsfiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM