Spin wheel add component in Html and JS

Issue

Here i’m trying to add and needle on top as a stopper. previously i was using custom created svg for arrow now i’m trying to replace that arrow with and needle.png at same position please suggest something i tried several options to add image in js but that doesn’t worked here.



<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">


      <link rel="stylesheet" href="../css/style.css">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
    <script src="//cdn.jsdelivr.net/npm/[email protected]"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>

    <title>GameOn</title>


</head>

<body>
    <section>

        <div class="modal spinWheel-modal fade" id="spin-modal" tabindex="-1" aria-labelledby="spin-modal" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">   
                    <div class="modal-header mb-1">
                        <div class="modal-close text-end mt-2">
                        <button type="button" class="btn-close text-end" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>

                        <h5 class="modal-title " id="spin-modalLabel" >spin the wheel & win</h5>
                    </div>
                    <div class="modal-body">
                        <div id="chart">
                            
                        </div>
                        <div id="question">
                            <h1></h1>
                        </div>
                        
                    </div>
                    <div class="modal-footer text-center">
                        <div class="footer-button">
                            <a href="./faq.html" >
                                <button type="button" class="btn btn-danger" >How to play?</button>
                            </a>
                        </div>
                        <div class="footer-text mt-3">
                            <a href="./help.html">
                                <h6>Term & Conditions</h6>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

         </section>

    <script>
        
        var padding = { top: 0, right: 0, bottom: 0, left: 0 },
            w = 250 - padding.left - padding.right,
            h = 275 - padding.top - padding.bottom,
            r = Math.min(w, h) / 2,
            rotation = 0,
            oldrotation = 0,
            picked = 100000,
            oldpick = [],
            color = d3.scale.category20();//category20c()
        
        var data = [
            { "label": "100 Coins", "value": "1", "question": "100" },
            { "label": "20 Coins", "value": "2", "question": "20" },
            { "label": "10 Coins", "value": "3", "question": "10" },
            { "label": "5 Coins", "value": "4", "question": "5" },
            { "label": "5 Coins", "value": "4", "question": "5" },
        ]
        var svg = d3.select('#chart')
            .append("svg")
            .data([data])
            .attr("width", w + padding.left + padding.right)
            .attr("height", h + padding.top + padding.bottom);
        
        var container = svg.append("g")
            .attr("class", "chartholder")
            .attr("transform", "translate(" + (w / 2 + padding.left) + "," + (h / 2 + padding.top) + ")");
        
        var vis = container
            .append("g");
        
        var pie = d3.layout.pie().sort(null).value(function (d) { return 1; });
        
        // declare an arc generator function
        var arc = d3.svg.arc().outerRadius(r);
        
        var spindata;
        // select paths, use arc generator to draw
        var arcs = vis.selectAll("g.slice")
            .data(pie)
            .enter()
            .append("g")
            .attr("class", "slice");
        
        function playSound() {
            var audio = new Audio('tick.mp3');
            audio.play();
        }
        
        
        arcs.append("path")
            .attr("fill", function (d, i) { return color(i); })
            .attr("d", function (d) { return arc(d); })
            // .attr({"fill":"#000000"},"i", function (i) { return arc(i); });
            // .style({"#bbbb":"#dddd"});
        
        // add the text
        arcs.append("text").attr("transform", function (d) {
            d.innerRadius = 0;
            d.outerRadius = r;
            d.angle = (d.startAngle + d.endAngle) / 2;
            return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")translate(" + (d.outerRadius - 20) + ")";
        })
            .attr("text-anchor", "end")
            .style({"fill":"#ffffff"})
            .text(function (d, i) {
                return data[i].label;
            });
        
        container.on("click" , spin);
        container.on( "ontouchend", spin);
        
        
        function spin(d) {
        
            container.on( "click" ,  null);
            container.on( "ontouchend" ,  null);
            console.log("OldPick: " + oldpick.length, "Data length: " + data.length);
            if (oldpick.length == data.length) {
                container.on("click" , null);
                container.on("ontouchend" , null);
                return;
            }
        
            var ps = 360 / data.length,
                pieslice = Math.round(1440 / data.length),
                rng = Math.floor((Math.random() * 1440) + 360*10);
            callbacksound = setTimeout(function () { playSound() }, 1000);
        
            rotation = (Math.round(rng / ps) * ps);
        
        
            picked = Math.round(data.length - (rotation % 360) / ps);
            picked = picked >= data.length ? (picked % data.length) : picked;
        
        
            if (oldpick.indexOf(picked) !== -1) {
                d3.select(this).call(spin);
                return;
            } else {
                oldpick.push(picked);
            }
            rotation += 0 - Math.round(ps / 2);
        
            vis.transition()
                .duration(6000)
                .attrTween("transform", rotTween)
                .each("end",
                    function () {
        
                        //mark question as seen
                        d3.select(".slice:nth-child(" + (picked + 1) + ") path")
                            .attr("fill", "#BCBCBC");
        
                        spindata = data[picked].question;
        
                        Swal.fire({
                            title: "Congratulation !!",
                            html: "You Won " + spindata + " Coins",
                            confirmButtonColor: '#ffa000',
                            showClass: {
                                popup: 'animate__animated animate__fadeInDown'
                            },
                            hideClass: {
                                popup: 'animate__animated animate__fadeOutUp'
                            }
                        })
                            .then(function () {
        
                                window.location.href = "../html/header.html";
                            });
        
                        // alert("#question h1");
                        oldrotation = rotation;
        
                        // container.on("click" , "touchend", spin);
                    });
        }
        //make arrow
        
//         var arrow = document.createElement("arrow");
//  arrow.src = "./needle.png";
//  var src = document.getElementById("chart");
//  src.append("arrow");

        svg.append("g")
            .attr("transform", "translate(" + (w / 2 + padding.left + padding.right) + "," + ((h / h) + padding.top ) + ")")
            .append("path")
            .attr("d", "M-" + (r * 0.25) + ",0L0," + (r * .075) + "L0,-" + (r * .075) + "Z" )
            // .attr('needle.png');
            .style({ "fill": "#f4c91b", "transform": "rotate(270deg" });
        
        //draw spin circle
        container.append("circle")
            .attr("cx", 0)
            .attr("cy", 0)
            .attr("r", 35)
            .style({ "fill": "#f4c91b", "cursor": "pointer" });
        
        //spin text
        container.append("text")
            .attr("x", 0)
            .attr("y", 8)
            .attr("text-anchor", "middle")
            .text("SPIN")
            .style({ "font-weight": "bold", "font-size": "20px", fill: "#ed4c38" });
        
        
        function rotTween(to) {
            var i = d3.interpolate(oldrotation % 360, rotation);
            return function (t) {
                return "rotate(" + i(t) + ")";
            };
        }
        
        
        function getRandomNumbers() {
            var array = new Uint16Array(1000);
            var scale = d3.scale.linear().range([360, 1440]).domain([0, 100000]);
        
            if (window.hasOwnProperty("crypto") && typeof window.crypto.getRandomValues === "function") {
                window.crypto.getRandomValues(array);
                console.log("works");
            } else {
                //no support for crypto, get crappy random numbers
                for (var i = 0; i < 1000; i++) {
                    array[i] = Math.floor(Math.random() * 100000) + 1;
                }
            }
        
            return array;
        }
        
        
        setInterval(function() {
            var show1 =  $('#spin-modal').modal('show');
            if(show1) {
                $('#spin-modal').modal('show');
            }
            else{
                $('#spin-modal').modal('hide');
            }
          }, 1000);
                    </script>
   
    <!-- <script src="../js/spin.js"></script> -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
           integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
           crossorigin="anonymous"></script>
       <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"
           integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p"
           crossorigin="anonymous"></script>
       <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
           integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF"
           crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4"
        crossorigin="anonymous"></script>
</body>

</html>



Here i’m trying to add and needle on top as a stopper. previously i was using custom created svg for arrow now i’m trying to replace that arrow with and needle.png at same position please suggest something i tried several options to add image in js but that doesn’t worked here.

Solution

    let arrow = document.createElement("img");
    arrow.src = "./needle.png"
    arrow.alt = "needle"
    document.getElementById("chart").appendChild(arrow)

Add this at the end of the script tag. Make sure that the filepath is correct.

You next job will then be to position the image correctly. Which you can do by using position absolute.

To delete the previous arrow, delete this section:

        svg.append("g")
        .attr("transform", "translate(" + (w / 2 + padding.left + padding.right) + "," + ((h / h) + padding.top ) + ")")
        .append("path")
        .attr("d", "M-" + (r * 0.25) + ",0L0," + (r * .075) + "L0,-" + (r * .075) + "Z" )
        // .attr('needle.png');
        .style({ "fill": "#f4c91b", "transform": "rotate(270deg" });

Answered By – Noex98

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published