繁体   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