循环通过顺序命名的Canvases和顺序命名的图片对象的正确语法是什么...如此:我如何从这里开始:
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]);
为此......如何引用“canvas0Context”,“canvas1Context”,“canvas2Context”......和“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对象和canvas0Context
是画布的上下文。这意味着他们可以(并且可能应该)拥有id
或name
。使用document.getElementById()
你可以迭代它们。
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]);
}
更重要的是,您可以使用名称pic
命名所有画布,并迭代它们的集合:
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]);
}