Canvas绘制移动角色时水平镜像失效(翻转后消失)问题求助
解决Canvas角色朝向翻转消失的问题
你的问题出在缩放后坐标偏移导致角色被画出画布可视区域。直接调用ctx.scale(-1,1)会把整个画布沿Y轴翻转,原本的正X坐标会变成负的,角色就跑到画布外面去了。下面给你两种可行的解决方案:
方案一:正确使用save/restore + 平移修正
修改Follower的draw方法,在缩放前后加入平移操作,确保角色始终绘制在原位置:
this.draw = function() { ctx.imageSmoothingEnabled = false; const followerImage = canvasDetails.canvases.followersCanvas.assets['followerSpriteSheet']; const width = this.width; const height = this.height; const x = this.pos.x; const y = this.pos.y; ctx.save(); if (this.moveDir.x < 0) { // 先平移到角色右上角,缩放后再以新原点绘制,抵消偏移 ctx.translate(x + width, y); ctx.scale(-1, 1); ctx.drawImage(followerImage, 0, 0, width, height); } else { // 正常绘制 ctx.drawImage(followerImage, x, y, width, height); } ctx.restore(); }
原理:通过平移把坐标原点移到角色右侧,缩放后绘制相当于以角色自身右侧为轴翻转,保证位置不会偏移出画布。
方案二:直接用drawImage参数实现翻转(更简洁)
Canvas的drawImage支持通过设置宽度为负数实现水平镜像,无需修改上下文状态:
this.draw = function() { ctx.imageSmoothingEnabled = false; const followerImage = canvasDetails.canvases.followersCanvas.assets['followerSpriteSheet']; const width = this.width; const height = this.height; let x = this.pos.x; let drawWidth = width; if (this.moveDir.x < 0) { // 朝左时偏移x坐标,用负宽度实现镜像 x += width; drawWidth = -width; } ctx.drawImage(followerImage, x, this.pos.y, drawWidth, height); }
原理:负宽度会让drawImage从右往左绘制图像,实现水平翻转;同时偏移x坐标保证图像位置和原位置一致。
原代码无效的原因
你在save()后执行scale,但立刻调用restore()还原了状态,缩放操作还没作用到drawImage就被取消了;就算没还原,未修正的缩放坐标也会把角色画出画布可视区域。
内容的提问来源于stack exchange,提问作者Syn
相关产品推荐
相关产品推荐

