JavaScript实现跟随鼠标且炮管指向鼠标的坦克(圆形车身不旋转)代码修复
原有代码核心问题
- Canvas变换管理混乱:没有通过
save()/restore()隔离不同元素的变换范围,叠加了多层平移偏移,导致旋转效果无差别作用在所有后续绘制的图形上,坐标计算出现双倍偏移错误 - 炮管绘制坐标错位:在已经完成平移、旋转的本地坐标系中,仍然使用坦克的全局绝对坐标
this.x/this.y绘制矩形,导致炮管位置完全偏离预期 - 状态隔离不足:使用全局变量
baseAngle存储旋转角度,没有和坦克类的实例属性绑定,逻辑割裂
修复核心逻辑
- 严格使用Canvas的状态栈机制:每个独立的绘制块前后加
save()和restore(),保证变换的影响只作用在目标元素上,从根源上避免旋转效果影响圆形车身 - 拆分绘制流程:先画完全不受旋转影响的圆形车身,再单独给炮管设置独立的旋转变换,两者互不干扰
- 修正炮管的本地绘制坐标:在完成「将原点平移到坦克圆心→旋转到指向鼠标的角度」两步变换后,在本地坐标系下绘制炮管矩形,不再引用全局坐标
- 将旋转角度收归到类实例的
angle属性中,替换冗余的全局变量,减少全局状态污染
修复后完整可运行代码
// canvas variable var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); // browser window size var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; //set canvas size canvas.width = windowWidth; canvas.height = windowHeight; var mouseX = 0; var mouseY = 0; class Cannon { constructor(x,y, angle, size, speed){ this.x = x; this.y = y; this.angle = angle; this.size = size; this.speed = speed; } draw() { // 绘制无旋转的圆形车身 ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI); ctx.fillStyle = 'rgb(0,96,255)'; ctx.fill(); ctx.lineWidth = 3; ctx.strokeStyle = 'rgba(128,128,128)'; ctx.stroke(); ctx.closePath(); // 独立状态块绘制可旋转的炮管 ctx.save(); // 平移原点到坦克中心 ctx.translate(this.x, this.y); // 旋转到指向鼠标的角度 ctx.rotate(this.angle); // 本地坐标系下绘制炮管,沿x轴正方向伸出 ctx.beginPath(); ctx.rect(0, -this.size/2, this.size*2, this.size); ctx.fillStyle = 'rgb(192,192,192)'; ctx.fill(); ctx.lineWidth = 3; ctx.strokeStyle = 'rgba(128,128,128)'; ctx.stroke(); ctx.closePath(); ctx.restore(); } update() { // 原有移动逻辑完全保留 var dx = (mouseX - this.x)*.125; var dy = (mouseY - this.y)*.125; var dist = Math.sqrt(dx*dx + dy*dy); if(dist > this.speed){ dx *= this.speed / dist; dy *= this.speed / dist; } this.x += dx; this.y += dy; // 更新炮管朝向角度,指向鼠标 this.angle = Math.atan2(mouseY - this.y, mouseX - this.x); } } const newCannon = new Cannon(80,60, 1, 20, 7); onmousemove = function(e){ mouseX = e.clientX; mouseY = e.clientY; } function gameUpdate() { ctx.setTransform(1, 0, 0, 1, 0, 0); // 每帧重置全局变换 ctx.clearRect(0, 0, canvas.width, canvas.height); newCannon.update(); newCannon.draw(); requestAnimationFrame(gameUpdate); } gameUpdate();
<!DOCTYPE html> <html> <head> <title>CRUSH DEMO</title> <style> /* 清除浏览器默认边距,避免鼠标坐标偏移 */ * {margin: 0; padding: 0;} body {overflow: hidden;} </style> </head> <body> <canvas id="canvas"></canvas> </body> </html>
内容的提问来源于stack exchange,提问作者Karlos Margaritos
相关产品推荐
相关产品推荐

