如何在数组中声明具有不同上下文(ctx)的多个CANVAS?

时间:2019-06-18 19:34:57

标签: javascript html arrays canvas

我在HTML文件中使用了多个CANVAS,我想在数组中声明它们。这是(不是数组)声明:

var canvas0 = document.getElementById('canvas0');
var ctxPaint0 = canvas0.getContext('2d');
var canvas1 = document.getElementById('canvas1');
var ctxPaint1 = canvas1.getContext('2d');
var canvas2 = document.getElementById('canvas2');
var ctxPaint2 = canvas2.getContext('2d');
var canvas3 = document.getElementById('canvas3');
var ctxPaint3 = canvas3.getContext('2d');

为了对此进行优化,我尝试使用 For 循环,但是它不起作用:

var canvasArray = ["canvas0","canvas1","canvas2","canvas3"]; 
for (var i = 0; i < canvasArray.length; i++) { 

window["canvas"+i] = document.getElementById(canvasArray[i]);
window["ctxPaint"+i] = canvasArray[i].getContext('2d');

}

它输出此错误:

Uncaught TypeError: canvasArray[i].getContext is not a function

编辑: 感谢RSchneyer,现在可以将字符串数组更改为Canvas数组了:

let canvasArray = Array.from(document.getElementsByTagName("canvas"));
for (var i = 0; i < canvasArray.length; i++) { 

window["canvas"+i] = document.getElementById(canvasArray[i]);
window["ctxPaint"+i] = canvasArray[i].getContext('2d');

}

2 个答案:

答案 0 :(得分:1)

你可以喜欢

const ctxArray = [...document.querySelectorAll('[id^="canvas"]')].map(cvs => cvs.getContext('2d'));

这将导致包含所有canvas上下文的数组-这是您需要的,因为要使原始画布脱离上下文,您需要的就是:

let i = 0; // or any desired index
const canvas = ctxArray[i].canvas;

答案 1 :(得分:0)

canvasArray是一个字符串数组,没有getContext()函数。尝试将canvasArray[i]中的window["ctxPaint"+i] = canvasArray[i].getContext('2d');替换为window["canvas"+i],或创建另一个数组来保存实际的画布变量