Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add canvas dynamically with jquery

I've included all of my code in this fiddle: http://jsfiddle.net/RymyY/

My issues deal with the 'Add Shape' button on the left hand side.

I want to be able to add a new canvas every time the second add button is clicked, but i cannot get it to work. Similar code works in this fiddle here: http://jsfiddle.net/dzejkej/xwg5f/

I dont know why mine is not working. I have no idea whats wrong. Please help.

like image 615
dopatraman Avatar asked Dec 15 '11 15:12

dopatraman


1 Answers

You should not create multiple elements with the same ID as you are doing in the example code. document.getElementById('canvas'); always returns the first element with id "canvas", as it should.

var elementID = 'canvas' + $('canvas').length; // Unique ID

$('<canvas>').attr({
    id: elementID
}).css({
    width: rectWidth + 'px',
    height: rectHeight + 'px'
}).appendTo('#work_area');

var canvas = document.getElementById(elementID); // Use the created element

Here is a working example; http://jsfiddle.net/5b8NH/

like image 69
Stefan Avatar answered Sep 23 '22 19:09

Stefan