You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

类中draw函数里context.drawImage()条件传参问题求助

解决drawImage条件传参的语法错误

你的问题出在两个语法错误上:

  • 不能直接在函数参数列表中使用if语句块,函数参数需要的是表达式,而if是语句,不符合语法要求。
  • 你尝试的三元表达式写法错误:三元运算符a ? b : c只能返回单个值,用逗号分隔多个值会触发逗号运算符,最终只返回最后一个值,导致drawImage接收到的参数完全不符合要求。

正确的写法

因为只有第一个参数(图片)需要根据this.scared切换,其余参数完全相同,所以只需要对第一个参数使用三元表达式即可:

draw() {
  context.beginPath();
  context.arc(this.position.x,this.position.y, this.radius, 0, Math.PI * 2)
  context.fillStyle = this.scared ? 'blue' : this.color;
  context.fill();
  context.closePath();
  // 只对图片参数做条件判断,其余参数直接传入
  context.drawImage(this.scared ? this.imageScared : this.image, this.position.x -12, this.position.y -12)
}

另一种更清晰的写法(适合参数差异大的场景)

如果后续参数也需要条件切换,可以先提前赋值变量,再调用函数:

draw() {
  context.beginPath();
  context.arc(this.position.x,this.position.y, this.radius, 0, Math.PI * 2)
  context.fillStyle = this.scared ? 'blue' : this.color;
  context.fill();
  context.closePath();
  
  // 提前根据条件确定要使用的图片
  const targetImage = this.scared ? this.imageScared : this.image;
  // 统一调用drawImage
  context.drawImage(targetImage, this.position.x -12, this.position.y -12)
}

注意:你之前的三元判断逻辑搞反了——如果this.scared为真,应该使用this.imageScared而不是this.image,上面的代码已经修正了这个逻辑错误。

内容的提问来源于stack exchange,提问作者Maxswift

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 17:20:34