gpt4 book ai didi

javascript - Javascript动画 Canvas (人物运动)

转载 作者:行者123 更新时间:2023-11-30 14:44:43 24 4
gpt4 key购买 nike

我是javascript画布的新手,正在尝试弄清楚一些事情。我能够很好地创建人物,但是它的实际动作对我来说是棘手的。我能够在此找到有关如何挥手的帮助,但现在我想知道如何做更多。例如,是否可以使人物摇动,向右走然后上下跳动?



var canvas = document.getElementById("canvas");
context = canvas.getContext("2d"); // get Canvas Context object
let timestamp = Date.now();
let wave = false;


draw();

function draw() {
if(Date.now() < (timestamp+500)) return requestAnimationFrame(draw);

context.clearRect(0, 0, window.innerWidth, window.innerHeight);
context.beginPath();
context.fillStyle = "black"; // #000000
context.arc(200, 50, 30, 0, Math.PI * 2, true);
context.fill(); //fill the circle

context.beginPath();
context.lineWidth = 6;
context.stroke();

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

//arms
context.beginPath();
context.strokeStyle = "black";
context.moveTo(200, 100);
context.lineTo(150, 130);
if(wave) {
context.moveTo(200, 100);
context.lineTo(250, 130);
wave = false;
}
else {
context.moveTo(200, 100);
context.lineTo(250, 70);
wave = true;
}
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();
timestamp = Date.now();
requestAnimationFrame(draw);
}

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

最佳答案

装备和关键帧动画

最简单的动画是通过称为关键帧的方法。

动画的每个步骤都称为帧。对于电脑游戏,通常每秒60 -30帧(fps)

对于每一帧,您都需要在新位置绘制角色。以60fps播放5秒钟即300帧。

您可以创建绘制每个零件的x,y位置的300帧中的每一个的函数,但这是很多工作。

关键帧是通过仅在动画中创建一些特定关键点并让计算机在其间锻炼所有其他帧的方式来减轻工作量的一种方式。

动画循环

首先让我们设置动画循环。该函数每帧调用一次,我们用它来获取动画时间,清除画布并绘制动画。

requestAnimationFrame(mainLoop);  // request the first frame
var startTime; // we need to have start time to match all the animations to.
var gTime; // We use this as a global time. All animation functions will reference this time
function mainLoop(time){ // time is passed automatically by requestAnimationFrame
if(startTime === undefined){ // this is the first frame so set as the start time
startTime = time;
}
gTime = time - startTime;
// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);

/* the render code will go here */

requestAnimationFrame(mainLoop); // request the next frame

}


一个简单的对象。

最基本的说,我们可以通过对象的x,y位置为其设置动画。

我们创建了一个在某个位置绘制对象的函数。

function drawHead(x,y){
context.beginPath();
context.arc(x, y, 30, 0, Math.PI * 2, true);
context.fill();
}


在动画循环中,您现在可以绘制头部

drawHead(200,50);


但这不是动画

补间

下一步涉及创建关键帧并在它们之间进行插值。

假设我们有两个点 x1,y1x2,y2,我们想在它们之间移动一段时间,例如 time = 2秒。

为了找到 gTime = 1秒(半途)的位置,我们得到了两个点之间的差。

var dx = x2 - x1;
var dy = y2 - y1;


现在我们得到的时间是总时间的一小部分

var fTime = gTime / time; // 1 / 2 = 0.5


将时间作为分数,并将两个位置之间的差异乘以位置差异

dx *= fTime;
dy *= fTime;


将其添加到开始位置

var x = x1 + dx;    
var y = y1 + dy;


并且我们具有对象在1秒钟的位置。

我们可以压缩代码

var fTime = gTime / time;
var x = (x2 - x1) * fTime + x1;
var y = (y2 - y1) * fTime + y1;


对于动画,您将需要进行许多动画处理,因此可以创建一个通用函数,该函数将在给定开始时间和当前时间的任何两个数字之间进行补间。

// where v1, is start value, t1 is start time, 
// v2, is end value, t2 is end time,
// and gTime is the global time

function tweenValue(v1, t1, v2, t2, gTime){
// to get the fraction of time
// first how far from the start time (gTime - t1)
// divided by the time between t1,t1
// gives (gTime - t1) / (t2 - t1); get the fraction of time between t1, t2
// which we plug directly into the formular
return (v2 - v1) * ((gTime - t1) / (t2 - t1)) + x1;
}


定位关键帧

在动画中,您可能有100个关键帧。您需要具有根据当前时间定位正确关键帧的功能。这本身就是一门科学,因为有各种各样的方法可以优化搜索。现在,我们将使用最基本的搜索。

我们定义了一组关键帧,如下所示,其中x,y位置以及在这些位置的时间。

headKeys = [
{x : 200, y : 50, time : 0}, // x,y,time (time is in seconds
{x : 300, y : 50, time : 1},
{x : 200, y : 50, time : 2}, // last frame will loop back
]


现在,我们要查找当前时间需要哪些关键帧。当前时间可能在关键帧时间之外。为此,我们将循环播放所有键,因此,如果时间在关键帧时间之外,我们会将时间调整为在键内。

function findKeys(keys, gTime){
// first get total time of keys
var start = keys[0].time;
var end = keys[keys.length - 1].time;
var totalTime = end - start;
var time = gTime - start; // get time relative to the start time
// loop the time in to the time between the start and end time (we need to make sure negative time works as well
time = ((time % totalTime) + totalTime) % totalTime;
// now time is at some value between and including start and less than end

// Now find the keys
var index = 0; // index of the keys
while(index < keys.length){ // could use while(true) but JS will not optimize un-terminated loops so we avoid that
if(keys[index].time <= time && keys[index+1].time > time){ // are these the two keys??
return index; // return the index of the first key
}
index ++;
}
return -1; // This will never happen unless you have some bad values in the keys array
}


所以让它付诸行动



    const ctx = canvas.getContext("2d");
requestAnimationFrame(mainLoop);
var startTime;
var gTime;

//===============================================================================
// Animation code
function findKeys(keys, gTime){
var start = keys[0].time;
var end = keys[keys.length - 1].time;
var totalTime = end - start;
var time = gTime - start;
time = ((time % totalTime) + totalTime) % totalTime;
var index = 0;
while(index < keys.length){
if(keys[index].time <= time && keys[index+1].time > time){
return index;
}
index ++;
}
return -1;
}

function tweenValue(v1, t1, v2, t2, gTime){
return (v2 - v1) * ((gTime - t1) / (t2 - t1)) + x1;
}
function tweenCoords(key1, key2, gTime, result = {}){
var totalTime = key2.time - key1.time;
result.time = ((((gTime - key1.time) / totalTime) % 1) + 1) % 1;
result.x = (key2.x - key1.x) * result.time + key1.x;
result.y = (key2.y - key1.y) * result.time + key1.y;
return result;
}
//===============================================================================
// Character functions and animation data

const headKeys = [ // time in seconds, position in pixels
{x : 200, y : 50, time : 0},
{x : 300, y : 50, time : 1},
{x : 200, y : 50, time : 2},
];
const keyResult = {x : 0, y : 0, time : 0}; // this holds tween results and saves us creating objects each loop
function drawHead(x,y){
ctx.beginPath();
ctx.arc(x, y, 30, 0, Math.PI * 2, true);
ctx.fill();
}

function drawCharacter(gTime){
// draw the head
var keyIndex = findKeys(headKeys, gTime);
var headPos = tweenCoords(headKeys[keyIndex], headKeys[keyIndex +1], gTime, keyResult);
drawHead(headPos.x, headPos.y);
}


function mainLoop(time){
if(startTime === undefined){
startTime = time;
}
gTime = (time - startTime) / 1000; // convert time to seconds
ctx.clearRect(0,0,canvas.width,canvas.height);

drawCharacter(gTime)

requestAnimationFrame(mainLoop); // request the next frame
}


<canvas id="canvas" width="500" height="300"></canvas>





动画关节

到目前为止,我仅显示了如何对位置进行动画处理,但是在许多情况下,位置看起来并不理想。例如,挥舞着手臂的角色,如果您上下移动手,则手臂的长度会改变,然后变短,然后变长。

因此,您可以在角度之间补间,而不是在位置间补间。对于角色,这就是我们通常做所有关键帧(如角度)的方式。

我们在主体上选择一个点,并根据关键帧以正确的角度从该点抽出。

对于您的角色,我们将从臀部开始。

沿某个角度画一条线

function drawLine(x,y,angle,length){
ctx.beginPath();
ctx.lineTo(x,y);
ctx.lineTo(x + Math.cos(angle) * length, y + Math.sin(angle) * length);
ctx.stroke();
}


这个问题变得更加困难,因为您还将希望旋转连接到线路末端的所有物体。有很多方法可以做到这一点,现在它将使其变得非常简单。我们计算终点并将其用作下一个关节的起点。我们还将角度添加到下一行,因此下一行的总角度是其加上前一行的角度。

创建装备。

装备就是我们所描述的动画对象的描述。它描述了所有零件以及如何绘制它们。

以下是角色的简单装备

const man = {
parts: {
body: {
len: 60,
ang: -Math.PI / 2,
parts: {
arm1: {
len: 60,
ang: Math.PI * (9 / 8), // 1/8th is 22.5 deg
},
arm2: {
len: 60,
ang: Math.PI * (7 / 8), // 1/8th is 22.5 deg
},
neck: {
len: 20,
ang: 0,
parts: {
head: {
size: 10,
}
}
}
}
},
leg1: {
len: 60,
ang: Math.PI * (5 / 8), // 1/8th is 22.5 deg
},
leg2: {
len: 60,
ang: Math.PI * (3 / 8), // 1/8th is 22.5 deg
}
}
}


它是一个树形结构,其部分连接为子节点。因此,要找到您要跟随的头部 man.parts.body.parts.neck.parts.head角度是相对于上一个节点的。

为了绘制上述装备,我们使用了递归函数。



const man = {
parts: {
body: {
len: 60,
ang: -Math.PI / 2,
parts: {
arm1: {
len: 60,
ang: Math.PI * (9 / 8), // 1/8th is 22.5 deg
},
arm2: {
len: 60,
ang: Math.PI * (7 / 8), // 1/8th is 22.5 deg
},
neck: {
len: 20,
ang: 0,
parts: {
head: {
size: 10,
}
}
}
}
},
leg1: {
len: 60,
ang: Math.PI * (5 / 8), // 1/8th is 22.5 deg
},
leg2: {
len: 60,
ang: Math.PI * (3 / 8), // 1/8th is 22.5 deg
}
}
}


const ctx = canvas.getContext("2d");
const workPos = {
x: 0,
y: 0
}; // to hold working posints and save having to create them every frame

// this function get the end pos of a line at angle and len starting at x,y
function angLine(x, y, ang, len, pos = {}) {
pos.x = x + Math.cos(ang) * len;
pos.y = y + Math.sin(ang) * len;
return pos;
}

// draws a line
function drawLine(x, y, x1, y1) {
ctx.beginPath();
ctx.lineTo(x, y);
ctx.lineTo(x1, y1);
ctx.stroke();
}

// draws a circle
function drawCircle(x, y, size) {
ctx.beginPath();
ctx.arc(x, y, size, 0, Math.PI * 2);
ctx.fill();
}


// Recursively draws a rig.

function drawRig(x, y, ang, rig) {
var x1, y1, ang1;
if (rig.ang !== undefined) { // is this an angled line?
var end = angLine(x, y, ang + rig.ang, rig.len, workPos);
drawLine(x, y, end.x, end.y);
x1 = end.x;
y1 = end.y;
ang1 = ang + rig.ang;
} else if (rig.size) { // is this the head
drawCircle(x, y, rig.size);
x1 = x;
y1 = y;
ang1 = ang;
} else {
// if rig has a position move to that position to draw parts
x1 = ang.x !== undefined ? ang.x + x : x;
y1 = ang.y !== undefined ? ang.y + y : y;
ang1 = ang;

}
// are there any parts attached
if (rig.parts) {
// For each part attached to this node
for (const part of Object.values(rig.parts)) {
drawRig(x1, y1, ang1, part);
}
}
}


drawRig(250, 100, 0, man);

<canvas id="canvas" width="500" height="300"></canvas>





该装备是手动创建的,通常,装备是通过动画软件创建的。我使用自定义内部软件来创建装备和动画,但是您可以使用很多工具。 Google会帮助您找到它们。

补间钻机。

我的答案空间不足,因此将其保留在代码中。

我已将关键帧添加到装备中。 drawRig函数将使用关键帧(如果找到),否则仅使用正常位置 anglen

动画都散布在不同的长度上,因此组合的动画看起来比实际的更加复杂。

有关更多详细信息,请参见代码。



const ctx = canvas.getContext("2d");
const workPos = {x: 0, y: 0}; // to hold working posints and save having to create them every frame
requestAnimationFrame(mainLoop);
var startTime;
var gTime;

//===============================================================================
// Animation code
function findKeys(keys, gTime){
var start = keys[0].time;
var end = keys[keys.length - 1].time;
var totalTime = end - start;
var time = gTime - start;
time = ((time % totalTime) + totalTime) % totalTime;
var index = 0;
while(index < keys.length){
if(keys[index].time <= time && keys[index+1].time > time){
return index;
}
index ++;
}
return -1;
}

function tweenKeys(key1, key2, gTime, result = {}){
var totalTime = key2.time - key1.time;
result.time = ((((gTime - key1.time) / totalTime) % 1) + 1) % 1;
if (key1.x !== undefined) { result.x = (key2.x - key1.x) * result.time + key1.x }
if (key1.y !== undefined) { result.y = (key2.y - key1.y) * result.time + key1.y }
if (key1.ang !== undefined) { result.ang = (key2.ang - key1.ang) * result.time + key1.ang }
if (key1.len !== undefined) { result.len = (key2.len - key1.len) * result.time + key1.len }
if (key1.size !== undefined) { result.size = (key2.size - key1.size) * result.time + key1.size }
return result;
}

const keyResult = {x : 0, y : 0, ang : 0, len : 0, size : 0,time : 0}; // this holds tween results and saves us creating objects each loop

// this function get the end pos of a line at angle and len starting at x,y
function angLine(x, y, ang, len, pos = {}) {
pos.x = x + Math.cos(ang) * len;
pos.y = y + Math.sin(ang) * len;
return pos;
}

// draws a line
function drawLine(x, y, x1, y1) {
ctx.beginPath();
ctx.lineTo(x, y);
ctx.lineTo(x1, y1);
ctx.stroke();
}

// draws a circle
function drawCircle(x, y, size) {
ctx.beginPath();
ctx.arc(x, y, size, 0, Math.PI * 2);
ctx.fill();
}


// Recursively draws a rig.

function drawRig(x, y, ang, time, rig) {
var x1, y1, ang1, end, index;
if (rig.ang !== undefined) { // is this an angled line?
if(rig.keys){ // are there key frames???
index = findKeys(rig.keys, time);
tweenKeys(rig.keys[index], rig.keys[index+1], time, keyResult);
end = angLine(x, y, ang + keyResult.ang, keyResult.len, workPos);
rig.ang = keyResult.ang;
}else{
end = angLine(x, y, ang + rig.ang, rig.len, workPos);
}
drawLine(x, y, end.x, end.y);
x1 = end.x;
y1 = end.y;
ang1 = ang + rig.ang;
} else if (rig.size) { // is this the head
if(rig.keys){ // are there key frames???
index = findKeys(rig.keys, time);
tweenKeys(rig.keys[index], rig.keys[index+1], time, keyResult);
drawCircle(x, y, keyResult.size);
}else{
drawCircle(x, y, rig.size);
}
x1 = x;
y1 = y;
ang1 = ang;
} else {
// if rig has a position move to that position to draw parts
x1 = ang.x !== undefined ? ang.x + x : x;
y1 = ang.y !== undefined ? ang.y + y : y;
ang1 = ang;

}
// are there any parts attached
if (rig.parts) {
// For each part attached to this node
for (const part of Object.values(rig.parts)) {
drawRig(x1, y1, ang1, time,part);
}
}
}

// The stick man rig with keyframes

const man = {
parts: {
body: {
len: 60,
ang: -Math.PI / 2,
keys : [
{len : 60, ang : -Math.PI * (5 / 8), time : 0},
{len : 60, ang : -Math.PI * (3 / 8), time : 1.5},
{len : 60, ang : -Math.PI * (5 / 8), time : 3},
],
parts: {
arm1: {
len: 60,
ang: Math.PI * (9 / 8), // 1/8th is 22.5 deg
keys : [
{len : 60, ang : Math.PI * (10 / 8), time : 0},
{len : 60, ang : Math.PI * (8 / 8), time : 2},
{len : 60, ang : Math.PI * (10 / 8), time : 4},
],
},
foreArm2: {
len: 30,
ang: Math.PI * (7 / 8), // 1/8th is 22.5 deg
keys : [
{len : 30, ang : Math.PI * (7 / 8), time : 0},
{len : 30, ang : Math.PI * (4 / 8), time : 1},
{len : 30, ang : Math.PI * (7 / 8), time : 2},
],
parts : {
arm : {
len: 30,
ang: Math.PI * (7 / 8), // 1/8th is 22.5 deg
keys : [
{len : 30, ang : Math.PI * (1 / 8), time : 0},
{len : 30, ang : -Math.PI * (2 / 8), time : 0.5},
{len : 30, ang : Math.PI * (1 / 8), time : 1},
],
}
}

},
neck: {
len: 20,
ang: 0,
parts: {
head: {
size: 10,
}
}
}
}
},
leg1: {
len: 60,
ang: Math.PI * (5 / 8), // 1/8th is 22.5 deg
},
leg2: {
len: 60,
ang: Math.PI * (3 / 8), // 1/8th is 22.5 deg
keys : [
{len : 60, ang : Math.PI * (3 / 8), time : 0},
{len : 60, ang : Math.PI * (3 / 8), time : 4},
{len : 60, ang : Math.PI * (1 / 8), time : 4.5},
{len : 60, ang : Math.PI * (3 / 8), time : 5},
{len : 60, ang : Math.PI * (3 / 8), time : 8},
],
}
}
}




function mainLoop(time){
if(startTime === undefined){
startTime = time;
}
gTime = (time - startTime) / 1000; // convert time to seconds
ctx.clearRect(0,0,canvas.width,canvas.height);

drawRig(250, 100, 0, gTime, man);

requestAnimationFrame(mainLoop); // request the next frame
}

<canvas id="canvas" width="500" height="300"></canvas>





复杂动画

要创建复杂的动画,我们可以使用关键帧来设置关键帧集。例如,您可能有一个使用一组关键帧的步行动画,但是您没有为所有步行创建所有关键帧,而是仅创建了一个周期的关键,然后使用关键帧定义了多少次重复步行动画。

轻松功能

上面的补间都是线性的。在大多数情况下,这看起来并不自然。要解决此问题,请使用缓动功能。它们放置在补间功能中。

以下是一条 easeInOut曲线,从慢速开始加速,然后慢速向下减速。如下所示,将其添加到补间功能(从上面的片段中获取)。

const eCurve   = (v, p = 2) =>  v < 0 ? 0 : v > 1 ? 1 : Math.pow(v, p) / (Math.pow(v, p) + Math.pow(1 - v, p));} 
function tweenKeys(key1, key2, gTime, result = {}){
var totalTime = key2.time - key1.time;
result.time = ((((gTime - key1.time) / totalTime) % 1) + 1) % 1;
result.time = eCurve(result.time); // add the ease in out
... rest of function as normal

关于javascript - Javascript动画 Canvas (人物运动),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49135858/

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