如何在 HTML5 Canvas 中使用数字变量更改颜色?

问题描述 投票:0回答:1

我有一组行,我想根据js中的数值来填充它们。为什么这不起作用,我怎样才能使它起作用?

<!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>

我已经尝试了相同代码的多种变体,但它仍然不起作用,并且谷歌上没有任何关于它的内容

提前谢谢您

~箭头编程

javascript html variables colors html5-canvas
1个回答
0
投票

看起来您传递的字符串没有应用

a
的值。

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

如何使用反引号来应用

a
的值?

const a = 10;
const color = `rgb(${a * 5}, 200, 100)`;
© www.soinside.com 2019 - 2024. All rights reserved.