侧边栏壁纸
  • 累计撰写 225 篇文章
  • 累计创建 275 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

用canvas实现游戏手柄方向摇杆(joystick)

DGF
DGF
2023-05-31 / 0 评论 / 0 点赞 / 28 阅读 / 0 字

post212-1.png
摸鱼摸到canvas上了,那总得摸出点东西来吧,于是乎摸出了粗糙的方向摇杆,直接上代码吧。

canvas元素上绘制一个圆形摇杆,并且在鼠标移动时更新摇杆的位置。当鼠标移动到摇杆圆形范围内时,摇杆会跟随鼠标移动;当鼠标移动到摇杆圆形范围外时,摇杆会沿着鼠标与圆心的连线移动,直到到达圆形范围边缘。

HTML

<canvas id="joystick"></canvas>

JavaScript

var canvas = document.getElementById("joystick");
canvas.width = 500
canvas.height = 500
var ctx = canvas.getContext("2d");

var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 50;

function drawJoystick(x, y) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  ctx.fillStyle = "#CCCCCC";
  ctx.fill();
  ctx.lineWidth = 2;
  ctx.strokeStyle = "#333333";
  ctx.stroke();
  ctx.beginPath();
  ctx.arc(x, y, radius / 2, 0, 2 * Math.PI, false);
  ctx.fillStyle = "#333333";
  ctx.fill();
}

canvas.addEventListener("mousemove", function(event) {
  var rect = canvas.getBoundingClientRect();
  var x = event.clientX - rect.left;
  var y = event.clientY - rect.top;
  var distance = Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2));
  if (distance <= radius) {
    drawJoystick(x, y);
  } else {
    var angle = Math.atan2(y - centerY, x - centerX);
    var newX = centerX + radius * Math.cos(angle);
    var newY = centerY + radius * Math.sin(angle);
    drawJoystick(newX, newY);
  }
});

canvas.addEventListener("mouseleave", function() {
  drawJoystick(centerX, centerY);
});
0

评论区