javascript 使用 jquery 动态添加画布

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8522608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:42:25  来源:igfitidea点击:

add canvas dynamically with jquery

javascriptjqueryhtml5-canvas

提问by dopatraman

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

我已经在这个小提琴中包含了我的所有代码: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/

我希望能够在每次单击第二个添加按钮时添加一个新画布,但我无法让它工作。类似的代码在这个小提琴中工作:http: //jsfiddle.net/dzejkej/xwg5f/

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

我不知道为什么我的不工作。我不知道出了什么问题。请帮忙。

回答by Stefan

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.

您不应像在示例代码中那样创建多个具有相同 ID 的元素。 document.getElementById('canvas');总是返回 ID 为“canvas”的第一个元素,因为它应该。

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/

这是一个工作示例;http://jsfiddle.net/5b8NH/