javascript - 使用模板字符串通过函数绘制画布
问题描述
我想重构几个负责绘制不同类型的彩色框(奖金)的函数。我试着这样做:
function drawBonus(type) {
properties = {
type,
x: randomTen(0, width - 10),
y: randomTen(0, height - 10)
};
ctx.fillStyle = `${properties.type}Color`;
ctx.strokeStyle = `${properties.type}BorderColor`;
console.log(`${properties.type}Color`, `${properties.type}BorderColor`);
console.log(slowBonusColor, slowBonusBorderColor);
ctx.fillRect(properties.x, properties.y, 10, 10);
console.log(properties.type);
}
然后我调用了一个函数,希望这实际上会绘制指定的正方形。
drawBonus(`slowBonus`);
我定义了常量和文件的开头:
const slowBonusColor = "yellow";
const slowBonusBorderColor = "darkorange";
let properties;
虽然控制台日志实际上记录了我打算获得的内容,因此:slowBonusColor、slowBonusBorderColor,然后是黄色、深橙色,但画布绘图并未按预期执行。
有没有其他方法可以传递参数以根据特定细节获得奖金?我不希望有几个函数负责绘制不同类型的正方形。
解决方案
经过
ctx.fillStyle = `${properties.type}Color`;
您将字符串“slowBonusColor”分配给填充样式,而不是变量 slowBonusColor 的实际值。
如果该函数与变量 slowBonusColor 和其他函数在同一范围内,您可以尝试以下操作:
ctx.fillStyle = this[`${properties.type}Color`];
或者如果这些变量在全局范围内:
ctx.fillStyle = window[`${properties.type}Color`];
或者如果这些变量在一个对象中:
ctx.fillStyle = objOfVars[`${properties.type}Color`];
推荐阅读
- php - 将数组转换为字符串
- scala - Scala,Quill - 如何比较不区分大小写的值?
- html - 为什么我的媒体查询不适用于大分辨率?
- julia - Julia libllvm_system 未定义
- python - 在 Pycharm 中为 Django 项目打开数据库
- node.js - 在 Node 和 Typescript 的 Firebase 云函数中进行前置条件检查的简单方法是什么?
- php - 最纤细的 cURL 调用
- typescript - 打字稿不加载合并的声明
- javascript - 使用 JavaScript 更改用户输入的 URL 输出
- xml - 连接格式化的 XSLT 节点值的串联