Table of Contents
Understand coordinate calculations
Modify the update method of the Sword class
Complete code example
Summarize
Home Web Front-end HTML Tutorial Get coordinates of rotating sword in HTML Canvas

Get coordinates of rotating sword in HTML Canvas

Aug 22, 2025 pm 11:51 PM

Get coordinates of rotating sword in HTML Canvas

This article aims to help developers understand how to draw a rotating sword in HTML Canvas and get the endpoint coordinates of the sword. By analyzing the provided code, we will focus on how to correctly calculate the endpoint coordinates of the sword so that it can follow the character's arm and ultimately achieve the effect of a dynamically rotated sword. This article will provide modified code examples and explain the logic of the key parts.

Understand coordinate calculations

The key to drawing a rotating object in Canvas is to understand the transformation of the coordinate system. We need to determine the starting point of the sword (usually the position of the character's hand) and the end point. Since the sword is rotating, the end coordinates need to be calculated based on the rotation angle.

Modify the update method of the Sword class

In the original code, the update method of the Sword class has some problems when calculating the endpoint coordinates of the sword. The correct way to do this is to use the position of the left hand as one endpoint of the sword, and the position of the right hand as the other endpoint of the sword, and then calculate the other two endpoints based on the length of the sword. The following is the modified update method:

 update() {
    this.draw();
    this.Lx = LeftHand.x;
    this.Ly = LeftHand.y;
    this.Rx = RightHand.x;
    this.Ry = RightHand.y;

    this.Lsx = LeftHand.x;
    this.Lsy = LeftHand.y;
    this.Rsx = RightHand.x Player.swordLength;
    this.Rsy = RightHand.y Player.swordLength;
  }

explain:

  • this.Lx, this.Ly: The position of the left hand, as an endpoint of the sword.
  • this.Rx, this.Ry: The position of the right hand, as another endpoint of the sword.
  • this.Lsx, this.Lsy: The left hand position remains unchanged, as the third endpoint of the sword.
  • this.Rsx, this.Rsy: The right hand position plus the length of the sword, as the fourth endpoint of the sword.

Complete code example

The following is a modified complete code example, including the definitions of the player, leftHand, rightHand, and sword classes as well as the animate function.

 var c = document.getElementById("canvas");
var ctx = c.getContext("2d");

c.width = window.innerWidth;
c.height = window.innerHeight;

var mouse = { x: c.width / 2, y: c.height / 2 };

window.addEventListener("resize", function (event) {
  c.width = window.innerWidth;
  c.height = window.innerHeight;
});

window.addEventListener("mousemove", function (event) {
  mouse.x = event.clientX;
  mouse.y = event.clientY;
});

class player {
  constructor(x, y, r, color, v) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.v = v;
    this.color = color;
    this.swordLength = 200;
  }

  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.closePath();
  }

  update() {
    this.draw();
    var dy = mouse.y - this.y;
    var dx = mouse.x - this.x;
    const angle = Math.atan2(dy, dx);

    var vx = Math.cos(angle) * this.v;
    var vy = Math.sin(angle) * this.v;

    if (Math.abs(vx) > Math.abs(dx)) {
      vx = dx;
    }

    if (Math.abs(vy) > Math.abs(dy)) {
      vy = dy;
    }
    this.x = vx;
    this.y = vy;
  }
}

class leftHand {
  constructor(x, y, r, color) {
    this.x = x;
    this.y = y;
    this.color = color;
    this.angle = 0;
    this.r = r;
    this.Area = 40;
  }

  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.closePath();
  }

  update() {
    this.draw();
    this.x = Player.x this.Area * Math.cos(this.angle / 180);
    this.y = Player.y this.Area * Math.sin(this.angle / 180);
    this.angle = 30;
  }
}

class rightHand {
  constructor(x, y, r, color) {
    this.x = x;
    this.y = y;
    this.color = color;
    this.angle = 90;
    this.r = r;
    this.Area = 40;
  }

  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.closePath();
  }

  update() {
    this.draw();
    this.x = Player.x this.Area * Math.cos(this.angle / 180);
    this.y = Player.y this.Area * Math.sin(this.angle / 180);
    this.angle = 30;
  }
}

class sword {
  constructor(Lx, Ly, Rx, Ry, color, Lsx, Lsy, Rsx, Rsy) {
    this.Lx = Lx;
    this.Ly = Ly;
    this.Rx = Rx;
    this.Ry = Ry;
    this.Lsx = Lsx;
    this.Lsy = Lsy;
    this.Rsx = Rsx;
    this.Rsy = Rsy;
    this.color = color;
  }

  draw() {
    ctx.beginPath();
    ctx.moveTo(this.Lx, this.Ly);
    ctx.lineTo(this.Rx, this.Ry);
    ctx.lineTo(this.Rsx, this.Rsy);
    ctx.lineTo(this.Lsx, this.Lsy);
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.closePath();
  }

  update() {
    this.draw();
    this.Lx = LeftHand.x;
    this.Ly = LeftHand.y;
    this.Rx = RightHand.x;
    this.Ry = RightHand.y;

    this.Lsx = LeftHand.x;
    this.Lsy = LeftHand.y;
    this.Rsx = RightHand.x Player.swordLength;
    this.Rsy = RightHand.y Player.swordLength;
  }
}

const Player = new player(c.width / 2, c.height / 2, 30, "blue", 10);

const LeftHand = new leftHand(
  c.width / 2 40 * Math.cos(0 / 180),
  c.height / 2 40 * Math.sin(0 / 180),
  10,
  "red"
);

const RightHand = new rightHand(
  c.width / 2 40 * Math.cos(90 / 180),
  c.height / 2 40 * Math.sin(90 / 180),
  10,
  "yellow"
);

const Sword = new sword(
  c.width / 2 40 * Math.cos(0 / 180),
  c.height / 2 40 * Math.sin(0 / 180),
  c.width / 2 40 * Math.cos(90 / 180),
  c.height / 2 40 * Math.sin(90 / 180),
  "black",
  c.width / 2 40 * Math.cos(0 / 180),
  c.height / 2 40 * Math.sin(0 / 180),
  c.width / 2 40 * Math.cos(90 / 180),
  c.height / 2 40 * Math.sin(90 / 180)
);

function animate() {
  requestAnimationFrame(animate);
  ctx.clearRect(0, 0, c.width, c.height);
  Player.update();
  LeftHand.update();
  RightHand.update();
  Sword.update();
}

animate();

HTML code:

 


    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rotating Sword</title>


    <canvas id="canvas"></canvas>
    <script src="script.js"></script>

Make sure to save the JavaScript code to a file named script.js and reference it in the HTML file.

Summarize

By modifying the update method of the Sword class, we can correctly calculate the endpoint coordinates of the sword, thereby achieving the rotation effect of the sword. The key is to understand the coordinate transformation and how to calculate the correct endpoint coordinates based on the position of the character's arm and the length of the sword. Remember, canvas coordinate calculation is the basis for implementing complex animations. By mastering these concepts, you can create richer canvas animation effects.

The above is the detailed content of Get coordinates of rotating sword in HTML Canvas. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1600
276
How to embed a PDF document in HTML? How to embed a PDF document in HTML? Aug 01, 2025 am 06:52 AM

Using tags is the easiest and recommended method. The syntax is suitable for modern browsers to embed PDF directly; 2. Using tags can provide better control and backup content support, syntax is, and provides download links in tags as backup solutions when they are not supported; 3. It can be embedded through Google DocsViewer, but it is not recommended to use widely due to privacy and performance issues; 4. In order to improve the user experience, appropriate heights should be set, responsive sizes (such as height: 80vh) and PDF download links should be provided so that users can download and view them themselves.

How to add an icon to your website title tab in HTML How to add an icon to your website title tab in HTML Aug 07, 2025 pm 11:30 PM

To add an icon to the website title bar, you need to link a favicon file in part of the HTML. The specific steps are as follows: 1. Prepare a 16x16 or 32x32 pixel icon file. It is recommended to use favicon.ico to name it and place it in the website root directory, or use modern formats such as PNG and SVG; 2. Add link tags to HTML, such as PNG or SVG formats, adjust the type attribute accordingly; 3. Optionally add high-resolution icons for mobile devices, such as AppleTouchIcon, and specify different sizes through the sizes attribute; 4. Follow best practices, place the icon in the root directory to ensure automatic detection, clear the browser cache after update, and check the correctness of the file path.

Using HTML `input` Types for User Data Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

How to create a search input field in an HTML form How to create a search input field in an HTML form Aug 02, 2025 pm 04:44 PM

Usetheelementwithinatagtocreateasemanticsearchfield.2.Includeaforaccessibility,settheform'sactionandmethod="get"attributestosenddatatoasearchendpointwithashareableURL.3.Addname="q"todefinethequeryparameter,useplaceholdertoguideuse

Why is my HTML image not showing up? Why is my HTML image not showing up? Aug 16, 2025 am 10:08 AM

First, check whether the src attribute path is correct, and ensure that the relative or absolute path matches the HTML file location; 2. Verify whether the file name and extension are spelled correctly and case-sensitive; 3. Confirm that the image file actually exists in the specified directory; 4. Use appropriate alt attributes and ensure that the image format is .jpg, .png, .gif or .webp widely supported by the browser; 5. Troubleshoot browser cache issues, try to force refresh or directly access the image URL; 6. Check server permission settings to ensure that the file can be read and not blocked; 7. Verify that the img tag syntax is correct, including the correct quotes and attribute order, and finally troubleshoot 404 errors or syntax problems through the browser developer tool to ensure that the image is displayed normally.

How to use the HTML abbr tag for abbreviations How to use the HTML abbr tag for abbreviations Aug 05, 2025 pm 12:54 PM

Using HTML tags can improve the accessibility and clarity of content; 1. Mark abbreviations or acronyms with abbreviations; 2. Add title attributes to unusual abbreviations to provide a complete explanation; 3. Use when the document first appears, avoiding duplicate annotations; 4. You can customize the style through CSS, and the default browser usually displays dotted underscores; 5. It helps screen reader users understand terms and enhance user experience.

How to add an icon to a button in HTML How to add an icon to a button in HTML Aug 07, 2025 pm 11:09 PM

Using FontAwesome can quickly add icons by introducing CDN and adding icon classes to buttons, such as Like; 2. Using labels to embed custom icons in buttons, the correct path and size must be specified; 3. Embed SVG code directly to achieve high-resolution icons and keep them consistent with the text color; 4. Spacing should be added through CSS and aria-label should be added to the icon buttons to improve accessibility; in summary, FontAwesome is most suitable for standard icons, pictures are suitable for custom designs, while SVG provides the best scaling and control, and methods should be selected according to project needs. FontAwesome is usually recommended.

How to create a submit button that sends form data in HTML How to create a submit button that sends form data in HTML Aug 02, 2025 pm 04:46 PM

Use elements and set the action and method attributes to specify the data submission address and method; 2. Add input fields with name attribute to ensure that the data can be recognized by the server; 3. Use or create a submission button, and after clicking, the browser will send the form data to the specified URL, which will be processed by the backend to complete the data submission.

See all articles