0
I need to color several canvas, the code below colors one of them
var canvas1 = document.getElementById("a1");
var ctx1 = canvas1.getContext('2d');
ctx1.fillStyle = cor; //aqui vai a cor html
ctx1.fillRect(0, 0, 300, 300);
I can automate color through an array type arrcor = [#F95201,#AB31AA,#E70078...], something like:
ctx1.fillStyle = arrcor[i];
But I need each color of this to go to a different canvas according to the ID, something like id="a1", id="a2", id="A3"... So I need to automate this change, I tried to pass a variable in, like,:
rolln = "a" + i;
var canvas1 = document.getElementById(rolln);
var ctx1 = canvas1.getContext('2d');
ctx1.fillStyle = cor; //aqui vai a cor html
ctx1.fillRect(0, 0, 300, 300);
ou
var canvas1 = document.getElementById("a" + i);
var ctx1 = canvas1.getContext('2d');
ctx1.fillStyle = cor; //aqui vai a cor html
ctx1.fillRect(0, 0, 300, 300);
But it doesn’t work, as I do to change the id, according to i (counter) inside the loop since getElementById accepts only a string as parameter?
It should work. See the example in the OS in English https://stackoverflow.com/questions/22068387/can-i-use-a-string-variable-in-document-getelementbyid . Is your canvas in the DOM? This could be it...
– ricardogobbo
dib, it should work since
"a" + i
here is as much a string as"a1"
. See if the console shows an error, ifdocument.getElementById("a" + i)
find nothing, will give an error on the linevar ctx1 = canvas1.getContext('2d');
.– Sam
Exactly, that same mistake.
– dib