HTML5キャンバスアニメーションを作成する方法
要创建HTML5 canvas动画,需先设置canvas元素并获取2D上下文,然后使用requestAnimationFrame循环更新画面;例如绘制一个移动的蓝色圆形,通过不断清除画布并重绘其新位置实现动画效果,添加边界检测可让圆形碰到边缘时反弹,结合变量更新与绘图步骤即可实现流畅运动,最终可通过对象数组扩展为多个动画元素,整个过程依赖逐帧重绘和状态更新来模拟动态视觉效果。
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 ofsetInterval
– 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 サイトの他の関連記事を参照してください。

ホットAIツール

Undress AI Tool
脱衣画像を無料で

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

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

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

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

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

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

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

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

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

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

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

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

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

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

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