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?