add canvas dynamically with jquery

2019-05-16 11:36发布

问题:

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.

回答1:

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/