목차
좌표계를 이해하십시오
키 코드 분석 및 수정
완전한 코드 예제
웹 프론트엔드 HTML 튜토리얼 HTML 캔버스에서 회전하는 직사각형 검을 조정하십시오.

HTML 캔버스에서 회전하는 직사각형 검을 조정하십시오.

Aug 22, 2025 pm 11:48 PM

HTML 캔버스에서 회전하는 직사각형 검을 조정하십시오.

이 기사는 HTML 캔버스에서 회전 직사각형 검을 그리며 엔드 포인트 좌표를 얻는 문제를 해결하는 것을 목표로합니다. 기존 코드를 분석함으로써 검의 엔드 포인트 계산 방법이 명확 해지고 수정 된 검 () 기능은 칼이 캐릭터의 팔과 함께 회전되도록 제공됩니다. 동시에, 완전한 실행 가능한 코드 예제를 제공하여 개발자가 프로젝트에 직접 적용 할 수있는 편리합니다.

HTML 캔버스, 특히 검과 같은 무기에서 회전 사각형을 그리면 좌표 계산 및 각도 회전이 포함됩니다. 다음은 캔버스에서 회전하는 직사각형 칼의 좌표를 얻는 단계입니다.

좌표계를 이해하십시오

캔버스의 좌표계 원점 (0, 0)은 왼쪽 상단에 있습니다. x 축의 양의 방향은 오른쪽에 있고 y 축의 양의 방향은 아래쪽입니다. 모든 좌표 계산은이 기원을 기반으로합니다.

키 코드 분석 및 수정

Sword.update () 함수는 원본 코드에서 검의 끝점 좌표를 계산하여 칼의 잘못된 그림을 이끌어냅니다. 올바른 논리는 다음과 같습니다.

  • 왼손의 위치는 칼의 끝점입니다.
  • 오른쪽 위치는 검의 다른 종말점입니다.
  • 검의 다른 두 가지 종점은 Player.swordlength를 오른쪽 위치에 추가하여 결정할 수 있습니다.

따라서 다음과 같이 sword.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.wordlength;
  }

이 코드의 핵심은 칼의 모양과 회전이 팔의 움직임과 일치하도록 LSX, LSY, RSX 및 RSY의 값을 올바르게 설정하는 것입니다.

완전한 코드 예제

다음은 직접 복사하고 실행할 수있는 수정 된 완전한 코드 예제입니다.

 var c = document.getElementById ( "캔버스");
var ctx = c.getContext ( "2d");

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

var 마우스 = {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;
  마우스 .y = event.clienty;
});

클래스 플레이어 {
  생성자 (x, y, r, color, v) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.v = v;
    this.color = 색상;
    this.swordlength = 200;
  }

  그리다() {
    ctx.beginpath ();
    ctx.arc (this.x, this.y, this.r, 0, 2 * math.pi, false);
    ctx.fillstyle = this.color;
    ctx.fill ();
    ctx.closepath ();
  }

  업데이트() {
    this.draw ();
    var dy = mouse.y- this.y;
    var dx = mouse.x- this.x;
    const angle = math.atan2 (dy, dx);

    var vx = math.cos (각도) * this.v;
    var vy = math.sin (각도) * 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;
  }
}

클래스 lefthand {
  생성자 (x, y, r, color) {
    this.x = x;
    this.y = y;
    this.color = 색상;
    this.angle = 0;
    this.r = r;
    this.area = 40;
  }

  그리다() {
    ctx.beginpath ();
    ctx.arc (this.x, this.y, this.r, 0, 2 * math.pi, false);
    ctx.fillstyle = this.color;
    ctx.fill ();
    ctx.closepath ();
  }

  업데이트() {
    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;
  }
}

등급 {클래스 {
  생성자 (x, y, r, color) {
    this.x = x;
    this.y = y;
    this.color = 색상;
    this.angle = 90;
    this.r = r;
    this.area = 40;
  }

  그리다() {
    ctx.beginpath ();
    ctx.arc (this.x, this.y, this.r, 0, 2 * math.pi, false);
    ctx.fillstyle = this.color;
    ctx.fill ();
    ctx.closepath ();
  }

  업데이트() {
    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;
  }
}

클래스 칼 {
  생성자 (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 = 색상;
  }

  그리다() {
    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 ();
  }

  업데이트() {
    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.wordlength;
  }
}

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

const lefthand = 새로운 lefthand (
  C.Width / 2 40 * Math.Cos (0 / 180),
  C. Height / 2 40 * Math.Sin (0 / 180),
  10,
  "빨간색"
);

Const righthand = New Righthand (
  C.Width / 2 40 * Math.Cos (90 / 180),
  C. Height / 2 40 * Math.Sin (90 / 180),
  10,
  "노란색"
);

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),
  "검은색",
  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)
);

기능 애니메이션 () {
  requestAnimationFrame (애니메이션);
  ctx.clearRect (0, 0, C.Width, C.height);
  player.update ();
  lefthand.update ();
  Righthand.update ();
  sword.update ();
}

생기 있게 하다();

HTML 파일 :

 



  <meta charset="utf-8">
  <meta http-equiv="x-ua 호환" edge>
  <meta name="viewport" content="width = device-width, 초기 스케일 = 1.0">
  <title> 캔버스 소드 </title>
  
    몸 {
      여백 : 0;
      오버플로 : 숨겨진; / * 스크롤 바 방지 */
    }

    캔버스 {
      디스플레이 : 블록; / * 캔버스 아래에서 추가 공간을 제거 */
    }
  스타일>



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

  <cript>
    // 이전 응답의 JavaScript 코드가 여기에 있습니다
    var c = document.getElementById ( "캔버스");
    var ctx = c.getContext ( "2d");

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

    var 마우스 = {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;
      마우스 .y = event.clienty;
    });

    클래스 플레이어 {
      생성자 (x, y, r, color, v) {
        this.x = x;
        this.y = y;
        this.r = r;
        this.v = v;
        this.color = 색상;
        this.swordlength = 200;
      }

      그리다() {
        ctx.beginpath ();
        ctx.arc (this.x, this.y, this.r, 0, 2 * math.pi, false);
        ctx.fillstyle = this.color;
        ctx.fill ();
        ctx.closepath ();
      }

      업데이트() {
        this.draw ();
        var dy = mouse.y- this.y;
        var dx = mouse.x- this.x;
        const angle = math.atan2 (dy, dx);

        var vx = math.cos (각도) * this.v;
        var vy = math.sin (각도) * 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;
      }
    }

    클래스 lefthand {
      생성자 (x, y, r, color) {
        this.x = x;
        this.y = y;
        this.color = 색상;
        this.angle = 0;
        this.r = r;
        this.area = 40;
      }

      그리다() {
        ctx.beginpath ();
        ctx.arc (this.x, this.y, this.r, 0, 2 * math.pi, false);
        ctx.fillstyle = this.color;
        ctx.fill ();
        ctx.closepath ();
      }

      업데이트() {
        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;
      }
    }

    등급 {클래스 {
      생성자 (x, y, r, color) {
        this.x = x;
        this.y = y;
        this.color = 색상;
        this.angle = 90;
        this.r = r;
        this.area = 40;
      }

      그리다() {
        ctx.beginpath ();
        ctx.arc (this.x, this.y, this.r, 0, 2 * math.pi, false);
        ctx.fillstyle = this.color;
        ctx.fill ();
        ctx.closepath ();
      }

      업데이트() {
        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;
      }
    }

    클래스 칼 {
      생성자 (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 = 색상;
      }

      그리다() {
        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 ();
      }

      업데이트() {
        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.wordlength;
      }
    }

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

    const lefthand = 새로운 lefthand (
      C.Width / 2 40 * Math.Cos (0 / 180),
      C. Height / 2 40 * Math.Sin (0 / 180),
      10,
      "빨간색"
    );

    Const righthand = New Righthand (
      C.Width / 2 40 * Math.Cos (90 / 180),
      C. Height / 2 40 * Math.Sin (90 / 180),
      10,
      "노란색"
    );

    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),
      "검은색",
      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)
    );

    기능 애니메이션 () {
      requestAnimationFrame (애니메이션);
      ctx.clearRect (0, 0, C.Width, C.height);
      player.update ();
      lefthand.update ();
      Righthand.update ();
      sword.update ();
    }

    생기 있게 하다();
  스크립트>


</cript>

위 내용은 HTML 캔버스에서 회전하는 직사각형 검을 조정하십시오.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제

PHP 튜토리얼
1592
276
입력 태그의 이름 속성은 무엇입니까? 입력 태그의 이름 속성은 무엇입니까? Jul 27, 2025 am 04:14 AM

thenameattributeinanninputtagisusedtoifordite theOntify theOntify theOndeformissubmitted; itservessasekey-valuepairsentTotheserver, wheretheuser 's sinputisthevalue.1.whenaformissubmitted, whenaforted, thenameattributeBalueBecomesThevulueInThevalueInThevalueIntheAntheAnteAnteMOmesteAnteToTeServer

초보자를위한 필수 HTML 태그 초보자를위한 필수 HTML 태그 Jul 27, 2025 am 03:45 AM

HTML을 신속하게 시작하려면 웹 골격을 만들기 위해 몇 가지 기본 태그 만 마스터하면됩니다. 1. 페이지 구조는 필수적이며 루트 요소 인 메타 정보를 포함하며 컨텐츠 디스플레이 영역입니다. 2. 제목을 사용하십시오. 레벨이 높을수록 숫자가 작습니다. 레벨을 건너 뛰지 않도록 태그를 사용하여 텍스트를 분할하십시오. 3. 링크는 태그를 사용하고 HREF 속성과 일치하며 이미지는 태그를 사용하고 SRC 및 ALT 속성을 포함합니다. 4. 목록은 순서가없는 목록 및 주문 된 목록으로 나뉩니다. 각 항목은 표시되며 목록에 중첩되어야합니다. 5. 초보자는 모든 태그를 암기 할 필요가 없습니다. 글을 쓰는 동안 글을 쓰고 확인하는 것이 더 효율적입니다. 기본 웹 페이지를 만들기 위해 구조, 텍스트, 링크, 사진 및 목록을 마스터하십시오.

다른  태그 안에  태그를 넣을 수 있습니까? 다른 태그 안에 태그를 넣을 수 있습니까? Jul 27, 2025 am 04:15 AM

sinvalidhtml; browsersautomicallycloseThefirstbeOptenTenext, rentingInseparateParAgraphs.linlineElements, orforstylingwithinaparagraph, orforstylingwithinaparagraph, 또는 BlockContainers Orblockcontainers Orblockcontainers

HTML에 PDF 문서를 포함시키는 방법은 무엇입니까? HTML에 PDF 문서를 포함시키는 방법은 무엇입니까? Aug 01, 2025 am 06:52 AM

태그를 사용하는 것이 가장 쉽고 권장되는 방법입니다. 구문은 최신 브라우저가 PDF를 직접 포함시키는 데 적합합니다. 2. 태그를 사용하면 더 나은 제어 및 백업 컨텐츠 지원을 제공 할 수 있으며 구문은 지원되지 않을 때 백업 솔루션으로 태그의 다운로드 링크를 제공 할 수 있습니다. 3. Google Docsviewer를 통해 내장 할 수 있지만 개인 정보 및 성능 문제로 인해 널리 사용하는 것이 좋습니다. 4. 사용자 경험을 향상시키기 위해서는 적절한 높이를 설정해야하며 응답 크기 (예 : 높이 : 80VH) 및 PDF 다운로드 링크를 제공하여 사용자가 스스로 다운로드하여 볼 수 있도록해야합니다.

html에서 변정되지 않은 목록을 만드는 방법은 무엇입니까? html에서 변정되지 않은 목록을 만드는 방법은 무엇입니까? Jul 30, 2025 am 04:50 AM

HTML이 변절되지 않은 목록을 만들려면 목록 컨테이너를 정의하기 위해 태그를 사용해야합니다. 각 목록 항목은 태그로 포장되며 브라우저에는 총알이 자동으로 추가됩니다. 1. 태그로 목록을 만듭니다. 2. 각 목록 항목은 태그로 정의됩니다. 3. 브라우저는 기본 점 기호를 자동으로 생성합니다. 4. 하위 목록을 중첩을 통해 구현할 수 있습니다. 5. CSS의 목록 스타일 유형 속성을 사용하여 디스크, 원, 사각형 또는 없음과 같은 심볼 스타일을 수정하십시오. 이 태그를 올바르게 사용하여 표준 비 순응 목록을 생성하십시오.

Contentestable 속성을 사용하는 방법은 무엇입니까? Contentestable 속성을 사용하는 방법은 무엇입니까? Jul 28, 2025 am 02:24 AM

thecontentEditableAttributeMakesanyHtMlEmentEdivideTibledingContEntEditable = "true", intuusStrodifictlyContentInTheBrowser.2.itiscommonLyusedInrichTexTedItors, note-taking-interfaces, supportElementSlikediv

HTML에서 웹 사이트 제목 탭에 아이콘을 추가하는 방법 HTML에서 웹 사이트 제목 탭에 아이콘을 추가하는 방법 Aug 07, 2025 pm 11:30 PM

웹 사이트 제목 표시 줄에 아이콘을 추가하려면 HTML의 일부에서 Favicon 파일을 연결해야합니다. 특정 단계는 다음과 같습니다. 1. 16x16 또는 32x32 픽셀 아이콘 파일 준비. favicon.ico를 사용하여 이름을 지정하여 웹 사이트 루트 디렉토리에 배치하거나 PNG 및 SVG와 같은 최신 형식을 사용하는 것이 좋습니다. 2. PNG 또는 SVG 형식과 같은 HTML에 링크 태그를 추가하려면 유형 속성을 적절하게 조정하십시오. 3. 선택적으로 Appletouchicon과 같은 모바일 장치에 고해상도 아이콘을 추가하고 크기 속성을 통해 다양한 크기를 지정합니다. 4. 모범 사례를 따르고, 아이콘을 루트 디렉토리에 배치하여 자동 감지를 확인하고 업데이트 후 브라우저 캐시를 지우고 파일 경로의 정확성을 확인하십시오.

사용자 데이터에 html` 입력 '유형을 사용합니다 사용자 데이터에 html` 입력 '유형을 사용합니다 Aug 03, 2025 am 11:07 AM

올바른 htmlinput 유형을 선택하면 데이터 정확도를 향상시키고 사용자 경험을 향상 시키며 유용성을 향상시킬 수 있습니다. 1. 텍스트, 이메일, 전화, 번호 및 날짜와 같은 데이터 유형에 따라 해당 입력 유형을 선택하여 자동으로 체크섬 및 키보드에 적응할 수 있습니다. 2. HTML5를 사용하여보다 직관적 인 상호 작용 방법을 제공 할 수있는 URL, 색상, 범위 및 검색과 같은 새로운 유형을 추가하십시오. 3. 자리 표시 자 및 필요한 속성을 사용하여 양식 충전의 효율성과 정확성을 향상 시키지만 자리 표시자는 레이블을 대체 할 수 없다는 점에 유의해야합니다.

See all articles