Search code examples
javascriptjqueryhtmlcanvasjs

How to plot a canvasJS graph in canvas tag?


I have tried to plot the canvasJS graph in the canvas tag of HTML so I'm not able to do so I need some help..!

<html>
    <head>
        <script>
            window.onload = function () {

            var options = {
                title: {
                    text: "Desktop OS Market Share in 2017"
                },
                data: [{
                    type: "pie",
                    dataPoints: [
                        { y: 48.36, label: "Windows 7" },
                        { y: 26.85, label: "Windows 10" },
                        { y: 1.49, label: "Windows 8" },
                        { y: 6.98, label: "Windows XP" },
                        { y: 6.53, label: "Windows 8.1" },
                        { y: 2.45, label: "Linux" },
                        { y: 3.32, label: "Mac OS X 10.12" },
                        { y: 4.03, label: "Others" }
                    ]
                }]
            };
            $("#chartContainer").CanvasJSChart(options);

            }
        </script>
    </head>
    <body>
        <div>
            <canvas id="chartContainer" height="300" width="400"> </canvas>
        </div>
        <script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
        <script src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
    </body>
</html>

I want the graph to be plotted using the canvas tag but not by using div tag. Because once I use this code in the bootstrap template it comes out the panel allotted for the graph.

I want the graph to be plotted using the canvas tag but not by using div tag.


Solution

  • CanvasJS dynamically creates and adds Canvas to the chartContainer(div) provided. Changing canvas to div should work fine in your case. Please find the updated code below:

    var options = {
        title: {
            text: "Desktop OS Market Share in 2017"
        },
        data: [{
            type: "pie",
            dataPoints: [
                { y: 48.36, label: "Windows 7" },
                { y: 26.85, label: "Windows 10" },
                { y: 1.49, label: "Windows 8" },
                { y: 6.98, label: "Windows XP" },
                { y: 6.53, label: "Windows 8.1" },
                { y: 2.45, label: "Linux" },
                { y: 3.32, label: "Mac OS X 10.12" },
                { y: 4.03, label: "Others" }
            ]
        }]
    };
    $("#chartContainer").CanvasJSChart(options);
    <script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
    <script src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
    <div id="chartContainer" height="300" width="400"></div>