首页 > 解决方案 > 使用模板字符串通过函数绘制画布

问题描述

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

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

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

标签: javascriptcanvas

解决方案


经过

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`];

推荐阅读