目次
Set up the canvas element
Get the canvas context
Create a simple animation loop
Add collision detection (optional)
Key tips for better canvas animations
ホームページ ウェブフロントエンド H5 チュートリアル HTML5キャンバスアニメーションを作成する方法

HTML5キャンバスアニメーションを作成する方法

Sep 09, 2025 am 02:47 AM

要创建HTML5 canvas动画,需先设置canvas元素并获取2D上下文,然后使用requestAnimationFrame循环更新画面;例如绘制一个移动的蓝色圆形,通过不断清除画布并重绘其新位置实现动画效果,添加边界检测可让圆形碰到边缘时反弹,结合变量更新与绘图步骤即可实现流畅运动,最终可通过对象数组扩展为多个动画元素,整个过程依赖逐帧重绘和状态更新来模拟动态视觉效果。

How to create an HTML5 canvas animation

Creating an HTML5 canvas animation is straightforward once you understand the basics of the <canvas> element and JavaScript’s role in drawing and updating visuals over time. Here’s how to build a simple animation — like a moving circle — step by step.

Set up the canvas element

Start by adding a <canvas> element to your HTML file. Give it an id so you can reference it in JavaScript, and set width and height attributes.

<canvas id="myCanvas" width="800" height="400"></canvas>

You can style it with CSS if needed, but the actual drawing happens in JavaScript.

Get the canvas context

Inside a script tag or external JS file, get the 2D rendering context. This object provides methods and properties to draw and animate shapes.

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

Create a simple animation loop

Animations on canvas work by repeatedly clearing the canvas and redrawing elements in slightly different positions. Use requestAnimationFrame() to create a smooth, efficient loop.

function animate() {
    // Clear the canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Draw your frame (example: a moving circle)
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, Math.PI * 2);
    ctx.fillStyle = 'blue';
    ctx.fill();
    ctx.closePath();

    // Update position
    x += dx;
    y += dy;

    // Loop the animation
    requestAnimationFrame(animate);
}

// Initial position and movement
let x = 50;
let y = 50;
let dx = 3;
let dy = 2;
let radius = 20;

// Start the animation
animate();

This code moves a blue circle across the canvas. When it hits the edges, it will keep going off-screen unless you add boundary checks.

Add collision detection (optional)

To make the circle bounce off the walls, check its position against the canvas edges:

if (x + radius > canvas.width || x - radius < 0) {
    dx = -dx; // Reverse horizontal direction
}
if (y + radius > canvas.height || y - radius < 0) {
    dy = -dy; // Reverse vertical direction
}

Place this inside the animate() function before calling requestAnimationFrame.

Key tips for better canvas animations

  • Use requestAnimationFrame instead of setInterval – It syncs with the screen’s refresh rate for smoother performance.
  • Always clear the canvas – Use clearRect() at the start of each frame unless you want trailing effects.
  • Keep drawing code inside the animation loop – Anything you want to move or change must be redrawn each frame.
  • Separate logic from drawing – Update positions and states first, then draw.
  • Control speed with delta timing – For more advanced control, factor in time between frames to keep motion consistent across devices.

For example, you could expand this to animate multiple objects by storing them in an array:

const balls = [];

for (let i = 0; i < 5; i++) {
    balls.push({
        x: Math.random() * canvas.width,
        y: Math.random() * canvas.height,
        dx: Math.random() * 5 - 2.5,
        dy: Math.random() * 5 - 2.5,
        radius: Math.random() * 20 + 10,
        color: `rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255})`
    });
}

function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    balls.forEach(ball => {
        ctx.beginPath();
        ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
        ctx.fillStyle = ball.color;
        ctx.fill();
        ctx.closePath();

        // Update position
        ball.x += ball.dx;
        ball.y += ball.dy;

        // Bounce off walls
        if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0) {
            ball.dx = -ball.dx;
        }
        if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
            ball.dy = -ball.dy;
        }
    });

    requestAnimationFrame(animate);
}

animate();

Basically, that’s all you need to get started. Once you understand the animation loop and how to manipulate shapes over time, you can build anything from simple bouncing balls to games or data visualizations. The key is redrawing everything each frame and updating just enough to create the illusion of motion.

以上がHTML5キャンバスアニメーションを作成する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Stock Market GPT

Stock Market GPT

AIを活用した投資調査により賢明な意思決定を実現

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

ホットトピック

HTML5でカスタムコントロールを備えたオーディオプレーヤーを作成する方法は? HTML5でカスタムコントロールを備えたオーディオプレーヤーを作成する方法は? Sep 16, 2025 am 04:21 AM

最初に非表示のオーディオ要素を作成し、カスタムコントロールUIを作成し、再生、一時停止、進行状況調整、ボリュームコントロールなどの関数をJavaScriptを介してオーディオAPIに接続して、完全にパーソナライズされたオーディオプレーヤーを実現します。

HTML5でサーバーセントイベント(SSE)を使用する方法は? HTML5でサーバーセントイベント(SSE)を使用する方法は? Sep 21, 2025 am 06:11 AM

sseenablesseal-time、unidirectionalver-to-clientupdatesviahttp; useeventsourceinjavascripttoconnect、handlemessageswithonmessage、setserverresponsetypetotext/event-stream、formatdatawith "data:" and "and"&n "、andotionallalinalincludidsf

HTML5のアクセシビリティのためにフォーカスを管理する方法は? HTML5のアクセシビリティのためにフォーカスを管理する方法は? Sep 21, 2025 am 05:27 AM

useSemantichtmlelementslikeandfornative focusableandkeyboardsupport.ensurelogicaltaboderandvisiblefocusindicatorsviacss.proglivealmatelymanagefocusindynamiccontentlikemodalselement.focus()、trappingfocusinsideandeandeandeandeturningItafterosurair.Applyar

HTML5のアクセシビリティにARIAの役割を使用する方法は? HTML5のアクセシビリティにARIAの役割を使用する方法は? Sep 21, 2025 am 04:41 AM

ariaenhanceswebaccesibilitybyaddingsmantingtoelementswhentivenationhtmlisufficient.useariaroleslikerole = "button"、aria-expanded、andaria-labelforcustomcomponentsordynamiccontent、butalways-ferementive htmlementionsuchasbuttonav.update

HTML5で要素を適切に使用する方法は? HTML5で要素を適切に使用する方法は? Sep 17, 2025 am 06:33 AM

theTimeElementInhtml5representsDatesSandTimesInamachine-ReadableFormat、EnhingAccessibilityandseo; usethedatetimeattribute withiso-formattedvaluestoprovidesemantivine、特に特に人間と対応するために、存在すること、保証されていることを保証します

HTML5の正規表現に対してフォームフィールドを検証する方法は? HTML5の正規表現に対してフォームフィールドを検証する方法は? Sep 22, 2025 am 05:11 AM

usethepatternattributionhtml5inputelementStovalidateagainstaregex、sotsforpasswordsrequiringnumbers、上級、下皮、およびpairwithtitleforuserguidance and redquiredemptyentyencentyenceentyenceentyenceentyentyentyenced。

HTML5画像マップを応答する方法 HTML5画像マップを応答する方法 Sep 17, 2025 am 04:34 AM

HTML5イメージマップを応答するようにするには、JavaScriptを介して動的に調整するか、CSSを使用してオーバーレイ要素を絶対に配置できます。最初に、画像自体が応答性があることを確認し、次にページの読み込みとウィンドウ調整のときにJavaScriptを介した元のサイズの比率に従ってエリアエリアの座標を再計算するか、透明なリンクを使用して画像をパーセンテージポジショニングでカバーして、クロスデバイスの適応を実現し、最終的にインタラクティブな領域が画像と正確にスケーリングされるようにします。 2つの方法には、適用可能なシナリオがあります。 JavaScriptソリューションは元の構造と互換性があり、CSSソリューションはより単純で、スクリプトは必要ありません。プロジェクトのニーズに従って選択する必要があり、両方ともマルチスクリーン効果をテストし、タッチエリアが十分に大きいことを確認する必要があります。複雑なマップの簡単なレイアウトにJavaScriptメソッドを使用することをお勧めします。

HTML5ページにPDFドキュメントを埋め込む方法は? HTML5ページにPDFドキュメントを埋め込む方法は? Sep 21, 2025 am 05:08 AM

PDFを使用または埋め込みます。それはシンプルで直接的であり、代替コンテンツをサポートし、適切な互換性を持ち、境界から削除することができ、ニーズに応じて選択できます。

See all articles