Search code examples
javascripthtmlvariablescolorshtml5-canvas

How Can I Change a Color with a Numerical Variable in HTML5 Canvas?


I have a group of lines and I want to fill them according to numerical value in js. Why doesn't this work, and how can I make it work?

<!DOCTYPE html>
<html>
<head></head>
<body>
    <canvas id="myCanvas"></canvas>
</body>
<script>
    const a = 10;
    const color = "rgb(a * 5, 200, 100)";
    
    const c = document.getElementById("myCanvas");
    const ctx = c.getContext("2d");
    ctx.beginPath();
    ctx.moveTo(20, 20);
    ctx.lineTo(220, 100);
    ctx.lineTo(70, 100);
    ctx.strokeStyle = color;
    ctx.stroke();
</script> 
</html>

I already tried multiple variations of the same code, but it still doesn't work, and there is nothing on google about it

Thank you in advance

~Arrow.programming


Solution

  • It looks like you're passing a string without the expression a * 5 applied.

    const a = 10;
    const color = "rgb(a * 5, 200, 100)"; // "rgb(a * 5, 200, 100)"
    

    How about using a template literal so that the expression becomes applied?

    const a = 10;
    const color = `rgb(${a * 5}, 200, 100)`; // "rgb(50, 200, 100)"