Reputation: 359
I am trying to generate and draw shapes using HTML 5 canvas and JavaScript. I am trying to make it as DRY as possible but having some issues. I have the code as follows:
var sections = {
"w_end" : {
"name":"W End",
"id":"w_end",
"dimensions": {"move_to":[0,0], "coords":[[0,50], [50,50], [0,50]]}
}
}
$(document).ready(function() {
$.each(sections, function(k,v){
make_shape(k, v);
})
});
function make_shape(id, attributes) {
var holder = document.getElementById('room');
var grid_canvas = document.createElement("canvas");
holder.appendChild(grid_canvas);
grid_canvas.setAttribute("id", id);
var item = grid_canvas.getContext("2d");
item.fillStyle = "rgb(154,250,50)";
item.beginPath();
item.moveTo(attributes.dimensions.move_to[0],attributes.dimensions.move_to[1]);
$.each(attributes.dimensions.coords, function(k ,v){
item.lineTo(v[0],v[1]);
});
item.fill();
item.closePath();
}
This does not seem to work when pulling the lineTo
values from the json. I can switch the lineTo(v[0],v[1])
for lineTo(50,75)
inside the lopp and it generates a filled shape. I am not great at JavaScript as you can tell. Does anyone know what the issue is here and maybe give some advice on generating multiple shapes from some sort of list?
Cheers
Tony
Upvotes: 1
Views: 1456
Reputation: 6779
I played around with your code, it is flawless. There is no triangle drawn because somehow the path going back to itself fills nothing. Place only the first two vertices and it is OK.
"dimensions": {"move_to":[0,0], "coords":[[0,50], [50,50]]}
See this fiddle: http://jsfiddle.net/Nm7UQ/
Note that I commented out document.ready
.
Upvotes: 2