Need to do such a thing. Suppose there is an array, in it one of the elements (int) is responsible for the color of drawing primitives on the canvas . In a javascript loop, this array is drawn:

 for(var i = 0; i < obj.length; i++) { screen.fillStyle = obj[i].col;//как это сделать? scree это контекст canvas. fillStyle принимает что-то типа '#124578' или 'rgb(12,12,12)' screen.fillRect(obj[i].x, obj[i].y, obj[i].width, obj[i].height); } 

I have not the slightest idea how to implement it, but I really need it!


transferred from the “answer”:

let's assume in the variable i some difference between the color of the displayed objects.

 screen.fillStyle = 'rgb('+i*60+', 20, '+i*45+')'; 
  • Well, so, and how do you want to determine - exactly what color to draw? - Grundy

2 answers 2

I recommend to give a hex view:

 function getColor(index) { return '#' + getColorPart(42.5 * index) + getColorPart(42.5 * index) + getColor(0); } function getColorPart(num) { num = ~~num; // быстрее чем Math.floor var res = (0xff > num ? 0xff : 0x0 > num ? 0x00 : num).toString(16); return res.length === 1 ? res + '0' : res; } var _array = [1,2,3,4,5]; for (var i = 0, ii = _array.length; i < ii; ++i) { ctx.fillStyle = getColor(i); ctx.fillRect(0, i*25, 25, 25); } 

    Since this property is a regular string with color, you can collect it as you please, simply generating the desired string using the desired field.
    Examples can be seen in the help.

     function draw() { var ctx = document.getElementById('canvas').getContext('2d'); for (var i=0;i<6;i++){ for (var j=0;j<6;j++){ ctx.fillStyle = 'rgb(' + Math.floor(255-42.5*i) + ',' + Math.floor(255-42.5*j) + ',0)'; ctx.fillRect(j*25,i*25,25,25); } } } draw(); 
     <canvas id='canvas'></canvas>