簡體   English   中英

如何在Javascript中引用按順序命名的HTML畫布和圖片對象?

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

循環通過順序命名的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]);
}

pic0pic1pic2 HTML對象和canvas0Context是畫布的上下文。 這意味着他們可以(並且可能應該)擁有idname 使用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]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM