score:1

Accepted answer

document.body.style.backgroundColor = "black";

    canvw = 500;
    canvh = 500;
    border = 6;

    clickState = 0;

    var canvas = d3.select("body")
                    .append("svg")      //Add an SVG to the body
                    .attr("width",canvw+2*border)
                    .attr("height",canvh+2*border)

    var canvbg = canvas.append("rect")
                    .attr("x",border)
                    .attr("y",border)
                    .attr("width",canvw)
                    .attr("height",canvh)
                    .attr("fill","white")
                    .attr("stroke","rgb(200,200,200)")
                    .attr("stroke-width",5)

    var mydiv = d3.select("body")
                    .append("div")
                    .attr("id","outputdiv")
                    .style("color","orange")

    canvas.on("mousedown", mousedownfx);

    canvas.on("mouseup", mouseupfx);

    canvas.on("mousemove",mousemovefx);

    canvas.on("mouseout",mouseoutfx);

    function mousedownfx() {
        clickState = 1;
        mydiv.text("Down")
    }

    function mouseupfx() {
        clickState = 0;
        mydiv.text("Up")
    }

    function mousemovefx() {
        mydiv.text(clickState)
        clickState = clickState + 1;
    }

    function mouseoutfx() {
        clickstate = 0;
    }
<script src="https://d3js.org/d3.v5.min.js"></script>

When you are setting the listeners you are calling the function change:

canvas.on("mousedown", mousedownfx());
canvas.on("mouseup", mouseupfx());
canvas.on("mousemove",mousemovefx());
canvas.on("mouseout",mouseoutfx());

To:

canvas.on("mousedown", mousedownfx);
canvas.on("mouseup", mouseupfx);
canvas.on("mousemove",mousemovefx);
canvas.on("mouseout",mouseoutfx);

This will pass the function, which will then be called when the button is clicked.


Related Query

More Query from same tag