Json应该内容:颜色,x坐标,y坐标
我的代码:给出错误“未捕获的 TypeError:无法调用 null 绘制(匿名函数)的方法 'getContext'”代码:
<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();
}
}
}
//问题是draw()我怎么能在这里传递JSON?
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>
参考: http: //jsfiddle.net/ByT58/6/ http://jsfiddle.net/ByT58/8/ 我可以使用带有外部 JSON 数据的 jQuery 以编程方式绘制 HTML5 Canvas x/y 点吗?