gpt4 book ai didi

javascript - 如何让我的绘图在 HTML5 Canvas 中移动?

转载 作者:可可西里 更新时间:2023-11-01 14:48:18 24 4
gpt4 key购买 nike

我有一个 HTML5 Canvas 和 Javascript。我怎样才能让它像移动它的胳膊和脚一样移动?

我尝试使用谷歌搜索一些教程但失败了。

附上我的图片和代码:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="canvascss.css">
</head>

<body>
<div>
<canvas id="canvas" width="400px" height="300px" >
Your browser does not support HTML5 Canvas element
</canvas>
</div>

<script>
var canvas = document.getElementById("canvas");
if (canvas.getContext("2d")) { // Check HTML5 canvas support
context = canvas.getContext("2d"); // get Canvas Context object

context.beginPath();
context.fillStyle = "black"; // #ffe4c4
context.arc(200, 50, 30, 0, Math.PI * 2, true); // draw circle for head
context.fill();

context.beginPath();
context.strokeStyle = "black"; // color
context.lineWidth = 3;
context.arc(200, 50, 20, 0, Math.PI, false); // draw semicircle for smiling
context.stroke();

// eyes
context.beginPath();
context.fillStyle = "black"; // color
context.arc(190, 45, 3, 0, Math.PI * 2, true); // draw left eye
context.fill();
context.arc(210, 45, 3, 0, Math.PI * 2, true); // draw right eye
context.fill();

// body
context.beginPath();
context.moveTo(200, 80);
context.lineTo(200, 180);
context.strokeStyle = "black";
context.stroke();

// arms
context.beginPath();
context.strokeStyle = "black"; // blue
context.moveTo(200, 80);
context.lineTo(150, 130);
context.moveTo(200, 80);
context.lineTo(250, 130);
context.stroke();

// legs
context.beginPath();
context.strokeStyle = "black";
context.moveTo(200, 180);
context.lineTo(150, 280);
context.moveTo(200, 180);
context.lineTo(250, 280);
context.stroke();
}

</script>

</body>
</html>

结果:

enter image description here

最佳答案

来自 HTML5 Canvas Animation with requestAnimFrame :

To create an animation using HTML5 Canvas, we can use the requestAnimFrame shim which enables the browser to determine the optimal FPS for our animation. For each animation frame, we can update the elements on the canvas, clear the canvas, redraw the canvas, and then request another animation frame.

简而言之,您的出发点如下:

requestAnimationFrame

您将需要一个 javascript 函数来更改起始图像的各个方面,然后定期调用该 javascript 代码。

setInterval 是另一个关键字,可以通过 google 和学习。

关于javascript - 如何让我的绘图在 HTML5 Canvas 中移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25420261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com