类中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
相关产品推荐
相关产品推荐

