使用模板字符串通过函数进行画布绘制

时间:2018-07-31 09:29:30

标签: javascript canvas

我想重构几个函数,这些函数负责绘制不同类型的彩色框(奖金)。我试图这样做:

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,然后是黄色,深橙色,但画布绘制并未按预期执行。

是否还有其他方法可以传递参数,以便根据特定的细节获得奖金?我不希望有几个函数负责绘制不同种类的正方形。

1 个答案:

答案 0 :(得分:0)

通过

ctx.fillStyle = `${properties.type}Color`; 

您将字符串“ slowBonusColor”分配给fillstyle,而不是变量slowBonusColor的实际值。

如果该函数与变量slowBonusColor和其他变量在同一作用域内,则可以尝试如下操作:

ctx.fillStyle = this[`${properties.type}Color`]; 

或这些变量是否在全局范围内:

ctx.fillStyle = window[`${properties.type}Color`];

或这些变量是否在对象中:

ctx.fillStyle = objOfVars[`${properties.type}Color`];