Here is my code:
$('#add_shape').click(function() {
var rectHeight = $('#rect_height_input').val();
var rectWidth = $('#width_input').val();
$('<canvas>').attr({
id: 'canvas'
}).css({
height: function() {
if (rectHeight > 0) {
return rectHeight + 'px';
}
else {
return rectWidth + 'px';
}
},
width: rectWidth + 'px'
}).appendTo('#work_area');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = $('#color_list option:selected').val();
ctx.fillRect(0, 0, rectWidth, rectHeight);
});
When the #add_shape button is clicked, the rectangle does not show up. What am I missing here? Please help.
In response to previous revision:
You retrieved existing canvas element using
document.getElementById()and then you created another one using jQuery$('<canvas>')and appended it to#work_area.Change
$('<canvas>')into$(canvas)to use the already existing canvas.Did you really want to call
document.getElementById('canvas')instead ofdocument.createElement('canvas')? In the 1st case there must be already a canvas element in the DOM with theid="canvas"which looks suspicious.Edit #1 (in response to current revision):
If that was just a wrote code in the answer then check your HTML (which you should also provide). Your code is working as demonstrated in this fiddle.
Make sure that IDs are correct – You are using
#rect_height_inputfor height, but#width_inputfor width and double-check values for the color options – maybe the rectangle is drawin using white color.Edit #2 (in response to the fiddle in comments):
For each shape you create a new canvas element and all those elements have same (!) id. This is incorrect. Attribute
idof an element should be unique. In your code you will always get the first canvas and draw on it – now matter how many shapes you crated. Rest of canvas elements are empty.Your code is drawing rectangles correctly (apart from the “same canvas” problem). Try to draw rectangle with big height and width – it is working. When the width/height are very small then the canvas is too small to show the rectangle. Setting minimum width/height or using one big canvas and drawing shapes onto it is a way to go.