On button click open a new window and draw a circle with D3

强颜欢笑 提交于 2020-01-06 14:11:44

问题


I'm trying to open a new window on button click and draw a simple circle on it.

I can open a window but circle won't appear on it with this code. Any ideas on how to solve this.0

Here is my code:

function drawBarChart(newWindowRoot){
    var sampleSVG = d3.select(newWindowRoot)
        .append("svg")
        .attr("width", 100)
        .attr("height", 100);

    sampleSVG.append("circle")
        .style("stroke", "gray")
        .style("fill", "white")
        .attr("r", 40)
        .attr("cx", 50)
        .attr("cy", 50)
        .on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
        .on("mouseout", function(){d3.select(this).style("fill", "white");});
}
function createNewPage(){

    var button = content.append("button")
            .attr("class", "button")
            .attr("id", "myButton")
            .text("Visualize");

    document.getElementById("myButton").onclick = function () {

        var newWindow = window.open('');
        newWindowRoot = d3.select(newWindow.document.body)
            .attr("width","1060px")
            .attr("margin","50px auto");

        drawBarChart(newWindowRoot);

    }

}

回答1:


When you call drawBarChart(newWindowRoot), you're passing a d3 selection — the result of d3.select(newWindow.document.body) — into that function. That makes sense.

However, from within drawBarChart, you call var sampleSVG = d3.select(newWindowRoot), essentially making a d3 selection of a d3 selection. That doesn't work (unlike what you might expect from jQuery). You should skip that latter d3.select and that'll make your code begin to work. More specifically, that'll make the button appear in the new window, but not the circle.

To make the circle appear, you need to fix another issue: Your fiddle attempts to add the circle to the button, instead of to an SVG (this is different than your example above which isn't trying to create a button).

Here's a working fiddle

By the way, the reason the jsFiddle you linked to didn't work is because the link you embedded was using secure protocol (https) and the jsfiddle functionality that was trying to load d3 is insecure (http), which resulted in a failure to load d3 and in turn an error executing your code.



来源:https://stackoverflow.com/questions/29654130/on-button-click-open-a-new-window-and-draw-a-circle-with-d3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!