0

Json should content : color, x-cordinate, y-cordinate

My Code: Giving Error "Uncaught TypeError: Cannot call method 'getContext' of null draw (anonymous function) " Code:

<head>
<style>
body {
        margin: 0;
        padding: 40px 0 0;
        background: #efefef;
    }
    .canvas-wrap {
        background: #fff;
        margin: 0 auto;
        width: 200px;
        height: auto;
    }
</style>
<script src="jquery-1.7.min.js"></script>

<script>
function draw(data) {
    //var ctx = document.getElementsByTagName('canvas')[0].getContext('2d');
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");

    // set attributes for all circles
    var radius = 7;

    // set attributes for all lines
    ctx.lineWidth = 5;
    ctx.lineJoin = 'round';

    for(var key in data) {
        var x = data[key].x;
        var y = data[key].y;
        ctx.fillStyle = data[key].color;
        for(var i = 0; i < x.length; ++i) {
            ctx.beginPath();
            ctx.arc(x[i], y[i], radius, 0, Math.PI * 2, true);
            ctx.fill();
            ctx.closePath();
        }

    }
}

//problem is draw() how can I pass JSON here?

draw({
    red:  { color: "#E51919", x: [20,50], y:[20, 50] },
    blue: { color: "#133175", x: [100], y:[50] },
    green: { color: "green", x: [10], y:[50] }
});
</script>

</body oonload="draw(this)>
<div class="canvas-wrap">
    <canvas id="myCanvas" width="200" height="115"></canvas>
</div>
</body>

Ref :http://jsfiddle.net/ByT58/6/ http://jsfiddle.net/ByT58/8/ Can I plot HTML5 Canvas x/y points programatically using jQuery with external JSON data?

Community
  • 1
  • 1
fmt.Fprint
  • 617
  • 2
  • 7
  • 16
  • What external JSON file? Currently you just are [calling `draw(…)` too early](http://stackoverflow.com/q/14028959/1048572) – Bergi Jun 21 '13 at 08:44
  • Json data= [ { "color": "#E51919", "x": ["10", "20"], "y": ["10", "20"] }, { "color": "#133175", "x": ["40", "20"] "y": ["30", "40"] } ]; I want to pass these – fmt.Fprint Jun 21 '13 at 08:47
  • That seems to be neither JSON nor external. Where is that file located? – Bergi Jun 21 '13 at 08:49
  • In the reference example they are passing data with data({}) .... but i want to pass json object containing "color, x cordinate, y cordinate". Any reference for the same with pure javascript? – fmt.Fprint Jun 21 '13 at 08:56
  • I will be posting my answer soon. – fmt.Fprint Jun 21 '13 at 10:35
  • You’ve presented too little info for a good answer, but in general: “Cannot call method getContext of null” would normally be if your canvas variable is not referencing a valid canvas element. And your question “how can I pass JSON here” would be answered by this link: http://api.jquery.com/jQuery.getJSON/ – markE Jun 21 '13 at 13:36

0 Answers0