简体   繁体   中英

How to refer to sequentially named HTML Canvases and Picture Objects in Javascript?

what is the correct syntax for looping through sequentially named Canvases and sequentially named picture objects... like so: How do I go from this:

canvas0Context.drawImage(pic0 ,shapePositionX[0], shapePositionY[0], pic0.width * shapeScaleX[0], pic0.height * shapeScaleY[0]);
canvas1Context.drawImage(pic1 ,shapePositionX[1], shapePositionY[1], pic1.width * shapeScaleX[1], pic1.height * shapeScaleY[1]);
canvas2Context.drawImage(pic2 ,shapePositionX[2], shapePositionY[2], pic2.width * shapeScaleX[2], pic2.height * shapeScaleY[2]);

To this.....how to refer to "canvas0Context", "canvas1Context", "canvas2Context"...and "pic0", "pic1", "pic2"?

for( counter = 0; counter <= 2; counter++){
    canvas0Context.drawImage(pic0 ,shapePositionX[counter], shapePositionY[counter], pic0.width * shapeScaleX[counter], pic0.height * shapeScaleY[counter]);
}

pic0 , pic1 , pic2 html objects, and canvas0Context is the context of a canvas. That means they could (and possibly should) have an id or name . Using document.getElementById() you can iterate over them.

for(counter = 0; counter <= 2; counter++){
    let pic = document.getElementById("pic"+counter);
    let canvasContext = document.getElementById("canvas"+conter).getContext("2d");
    canvasContext.drawImage(pic, shapePositionX[counter], shapePositionY[counter], pic.width * shapeScaleX[counter], pic.height * shapeScaleY[counter]);
}

Even more, you could name all of the canvas with the name pic and iterate over the collection of them:

let pics = document.getElementByName("pic")
let canvasContexts = [];
document.getElementById("canvas"+conter).forEach((e) => {canvasContext.push(e.getContext("2d");})

for (let i in document.getElementByName("pic")) {
    canvasContexts[i].drawImage(pics[i], shapePositionX[counter], shapePositionY[counter], pics[i].width * shapeScaleX[counter], pics[i].height * shapeScaleY[counter]);
}

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