简体   繁体   中英

Do multiple canvas elements

I want to create multiple canvas elements with an id for each. What would the best approach be? Looking for a vanilla javascript solution.

var parent = document.createElement("parent");
var mycanvas1 = document.createElement("canvas");
mycanvas.id = "students";
document.getElementById("parent").appendChild(mycanvas1);

var mycanvas2 = document.createElement("canvas");
mycanvas.id = "classBadge";
document.getElementById("parent").appendChild(mycanvas2);

var mycanvas3 = document.createElement("canvas");
mycanvas.id = "classMaster";
document.getElementById("parent").appendChild(mycanvas3);

You could store your different canvas ids inside an array and iterate over it, like in the example below.

Note: You need to use the browser inspect tool to actually see the result, since the canvas elements are empty

 // Create "parent" element and append it to the DOM const parent = document.createElement("parent"); document.body.appendChild(parent) // Iterate over an array to create new elements const canvasIds = ['students', 'classBadge', 'classMaster'] canvasIds.forEach(id => { const canvas = document.createElement("canvas"); canvas.id = id parent.appendChild(canvas); }) 

You could create a reusable function that takes as argument the desired new canvas ID

 function createCanvas(canvasId) { const cvs = document.createElement("canvas"); cvs.id = canvasId; document.getElementById('parent').appendChild(cvs); } createCanvas("students"); createCanvas("classBadge"); createCanvas("classMaster"); 
 canvas {outline: 1px solid red;} 
 <div id="parent"></div> 

Since probably you're going to use your canvas element after creation, you could additionally expand the above to create a callback and use it like:

 function createCanvas(canvasId, cb) { const cvs = document.createElement("canvas"); cvs.id = canvasId; document.getElementById('parent').appendChild(cvs); if (cb) cb.call(cvs); } createCanvas("students", function() { // Canvas is created, use `this` to reference your new canvas Element console.log(this.id); }); 
 canvas {outline: 1px solid red;} 
 <div id="parent"></div> 

If you prefer not to use callbacks - than you could make your function return the created canvas:

 function createCanvas(canvasId, cb) { const cvs = document.createElement("canvas"); cvs.id = canvasId; document.getElementById('parent').appendChild(cvs); return cvs; } const studentsCanvas = createCanvas("students"); console.log(studentsCanvas.id); 
 canvas {outline: 1px solid red;} 
 <div id="parent"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM