创建与时间相关的圆圈动画

2024-02-16

嗨,我尝试制作动画。调用函数时绘制的 3 个圆圈之一应从右向左移动,首先应在画布上绘制一个随机(黄色、蓝色或橙色)圆圈,然后在 3 秒后绘制下一个随机圆圈,然后在 2 秒后, 8秒到现在为止。 我怎样才能做到这一点?现在,当主循环再次开始运行时,每次都会再次绘制圆圈。

    window.onload = window.onresize = function() {
  var C = 1; // canvas width to viewport width ratio
  var el = document.getElementById("myCanvas");


  var viewportWidth = window.innerWidth;
  var viewportHeight = window.innerHeight;

  var canvasWidth = viewportWidth * C;
  var canvasHeight = viewportHeight;
  el.style.position = "fixed";
  el.setAttribute("width", canvasWidth);
  el.setAttribute("height", canvasHeight);
  var x = canvasWidth / 100;
  var y = canvasHeight / 100;
var ballx = canvasWidth / 100;
var n;


  window.ctx = el.getContext("2d");
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  // draw triangles


  function init() {
        ballx;      
        return setInterval(main_loop, 1000);
  }
  function drawcircle1()
  {
  var radius = x * 5;
    ctx.beginPath();
      ctx.arc(ballx * 108, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
      ctx.fillStyle = 'yellow';
      ctx.fill(); 
  }
function drawcircle2()
  {
  var radius = x * 5;
    ctx.beginPath();
      ctx.arc(ballx * 108, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
      ctx.fillStyle = 'blue';
      ctx.fill(); 
  }
  function drawcircle3()
  {
  var radius = x * 5;
    ctx.beginPath();
      ctx.arc(ballx * 105, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
      ctx.fillStyle = 'orange';
      ctx.fill(); 
  }

  function draw() {   
        var counterClockwise = false;

   ctx.clearRect(0, 0, canvasWidth, canvasHeight);

    //first halfarc
   ctx.beginPath();
    ctx.arc(x * 80, y * 80, y * 10, 0 * Math.PI, 1 * Math.PI, counterClockwise);
    ctx.lineWidth = y * 1;
    ctx.strokeStyle = 'black';
    ctx.stroke();

    //second halfarc
   ctx.beginPath();
    ctx.arc(x * 50, y * 80, y * 10, 0 * Math.PI, 1 * Math.PI, counterClockwise);
    ctx.lineWidth = y * 1;
    ctx.strokeStyle = 'black';
    ctx.stroke();

    //third halfarc
   ctx.beginPath();
    ctx.arc(x * 20, y * 80, y * 10, 0 * Math.PI, 1 * Math.PI, counterClockwise);
    ctx.lineWidth = y * 1;
    ctx.strokeStyle = 'black';
    ctx.stroke();



    // draw stop button
    ctx.beginPath();
      ctx.moveTo(x * 87, y * 2);
      ctx.lineTo(x * 87, y * 10);
      ctx.lineWidth = x;
      ctx.stroke();
      ctx.beginPath();
      ctx.moveTo(x * 95, y * 2);
      ctx.lineTo(x * 95, y * 10);
      ctx.lineWidth = x;
      ctx.stroke();


      function drawRandom(drawFunctions){
    //generate a random index
    var randomIndex = Math.floor(Math.random() * drawFunctions.length);

    //call the function
    drawFunctions[randomIndex]();
}
drawRandom([drawcircle1, drawcircle2, drawcircle3]);


  }

  function update() {
    ballx -= 0.1;


    if (ballx < 0) {
      ballx = -radius;         


    }

  }







  function main_loop() {
    draw();
    update();
    collisiondetection();

  }


  init();

            function initi() {
                console.log('init');
                // Get a reference to our touch-sensitive element
                var touchzone = document.getElementById("myCanvas");
                // Add an event handler for the touchstart event
                touchzone.addEventListener("mousedown", touchHandler, false);
            }

            function touchHandler(event) {
                // Get a reference to our coordinates div
                var can = document.getElementById("myCanvas");
                // Write the coordinates of the touch to the div
                if (event.pageX < x * 50 && event.pageY > y * 10) {
                    ballx += 1;
                } else if (event.pageX > x * 50 && event.pageY > y * 10 ) {
                    ballx -= 1;
                }

                console.log(event, x, ballx);

                draw();


            }
            initi();
            draw();
}

我对你的代码有点困惑,但我想我明白你想知道如何延迟每个圆圈开始向左移动的时间。

以下是如何以不同的延迟设置黄色、蓝色和橙色圆圈的动画:

  • 使用 javascript 对象定义 3 个圆圈并将所有定义存储在一个数组中。
  • Inside an animation loop:
    • 计算自动画开始以来已经过去了多少时间
    • 循环遍历数组中的每个圆
    • 如果圆的延迟时间过去了,则将其向左设置动画
  • 当所有 3 个圆圈都移出屏幕左侧时,停止动画循环。

下面是带注释的代码和演示:

// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasWidth=canvas.width;
var canvasHeight=canvas.height;

// predifine PI*2 because it's used often
var PI2=Math.PI*2;

// startTime is used to calculate elapsed time
var startTime;

// define 3 circles in javascript objects and put
// them in the arcs[] array
var arcs=[];
addArc(canvasWidth,canvasHeight/2,20,0,PI2,0,-1,'yellow');
addArc(canvasWidth,canvasHeight/2+40,20,0,PI2,3000,-1,'blue');
addArc(canvasWidth,canvasHeight/2+80,20,0,PI2,8000,-1,'orange');

// begin animating
requestAnimationFrame(animate);


function animate(time){

  // set startTime if it isn't already set
  if(!startTime){startTime=time;}

  // calc elapsedTime
  var elapsedTime=time-startTime;

  // clear the canvas 
  ctx.clearRect(0,0,canvasWidth,canvasHeight);

  // assume no further animating is necessary
  // The for-loop may change the assumption 
  var continueAnimating=false;
  for(var i=0;i<arcs.length;i++){
    var arc=arcs[i];
    // update this circle & report if it wasMoved
    var wasMoved=update(arc,elapsedTime);
    // if it wasMoved, then change assumption to continueAnimating
    if(wasMoved){continueAnimating=true;}
    // draw this arc at its current position
    drawArc(arc);
  }

  // if update() reported that it moved something
  // then request another animation loop
  if(continueAnimating){
    requestAnimationFrame(animate);
  }else{
    // otherwise report the animation is complete
    alert('Animation is complete');
  }
}

function update(arc,elapsedTime){
  // has this arc's animation delay been reached by elapsedTime
  if(elapsedTime>=arc.delay){
    // is this arc still visible on the canvas
    if(arc.cx>-arc.radius){
      // if yes+yes, move this arc by the specified moveX
      arc.cx+=arc.moveX;
      // report that we moved this arc
      return(true);
    }
  }
  // report that we didn't move this arc
  return(false);
}

// create a javascript object defining this arc 
function addArc(cx,cy,radius,startAngle,endAngle,
                 animationDelay,moveByX,color){

  arcs.push({
    cx:cx,
    cy:cy,
    radius:radius,
    start:startAngle,
    end:endAngle,
    // this "delay" property is what causes this
    // circle to delay before it starts to animate
    delay:animationDelay,
    moveX:moveByX,
    color:color,
  });
}

// draw a given arc
function drawArc(a){
  ctx.beginPath();
  ctx.arc(a.cx,a.cy,a.radius,a.start,a.end);
  ctx.fillStyle=a.color;
  ctx.fill();
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=400 height=300></canvas>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

创建与时间相关的圆圈动画 的相关文章

  • 检测 iframe 内容加载失败

    我可以使用以下命令检测 iframe 的内容何时加载load事件 不幸的是 就我的目的而言 这有两个问题 如果加载页面时出现错误 404 500 等 则永远不会触发加载事件 如果某些图像或其他依赖项加载失败 则会照常触发加载事件 有什么方法
  • php在html页面中创建额外空间

    我是网络开发新手 我真的被这个愚蠢的问题困扰了 当我在 html 代码之前插入 php 代码时 如下所示 它在我的页面顶部创建了额外的空白空间 并将整个内容 推下 是否有可能以某种方式避免创建额外的空间 如果 php 代码位于 html 的
  • JSDoc:如何在生成的文档中包含自定义 css 文件模板?

    JS文档docs https jsdoc app about configuring default template html say 将图像目录复制到输出目录 复制全部 将 myproject static 中的静态文件复制到输出目录
  • 当我“显示:无”一个 SVG 时,另一个(独立的)SVG 会以不同的方式呈现

    我已经伤透了几个小时了 这没有任何意义 我将遇到的问题减少到这个codepen https codepen io Octopous pen OJORpJQ https codepen io Octopous pen OJORpJQ HTML
  • 如何将 HTML 表格转换为 csv 格式?

    是否有 HTML 解析器或某些库可以自动将 HTML 表格转换为 CSV 数据行 Here is http www unix com shell programming scripting 45274 html table csv html
  • t /= d 是什么意思? Python 和错误

    t current time b begInnIng value c change In value d duration def easeOutQuad swing function x t b c d alert jQuery easi
  • Relay 中的嵌套片段数据始终相同

    我是 Relay 新手 并且遇到了片段上嵌套数据的问题 当我在 graphiql 中进行测试时 以下查询返回正确的数据 因此我确信我的架构是正确的 viewer customers name billing address city 但是
  • 禁用任何类型的浏览器窗口滚动?

    有没有办法禁用滚动 不仅仅是滚动条 还有浏览器窗口的全部功能 根据您对 Keit 的回答 您不想在打开灯箱时滚动处于活动状态 如果是这种情况 您可以使用以下 css 在打开灯箱的同时向正文添加一个类 这个解决方案的好处是它保留了滚动 空间
  • Rxjs 可观察等待直到满足某些条件

    我有以下重试逻辑来重试操作 对于单个请求来说它工作得很好 对于多个正在进行的请求 我想在重试之前等待现有的重试逻辑完成 handleError errors Observable
  • Rails 4 - 带有 dependent-fields-rails 的条件 JS

    我正在尝试弄清楚如何在我的 Rails 4 应用程序中使用 dependent fields rails gem 我迷路了 我已将 underscore js 包含在我的供应商 javascripts 文件夹中 并更新了我的 applica
  • 在IOS中,引导模式中的iframe无法滚动

    我在引导程序模态体内有一个 iframe div class modal fade div class modal dialog div class modal content div class modal header div div
  • 如何检查jquery数据表中的每个复选框?

    我有一个第一列带有复选框的表格 我使用 jQuery DataTable 插件显示我的表格 我制作了 2 个链接来选择 取消选择每个复选框 这是选择全部的一个 a href Select all a 和 JavaScript functio
  • while 循环元素状态 cypress

    我有一个问题 我想单击一个按钮直到它消失 但次数可能会有所不同 所以我想检查可见性状态 当可见 true时单击按钮 当可见 false时结束测试 但问题是我不知道如何循环从获取元素到末尾的所有链 单击按钮一次 由于中断而停止 如果我删除中断
  • Javascript - 如何计算数字的平方?

    使用 JavaScript 函数 function squareIt number return number number 当给定数字 4294967296 时 函数返回 18446744073709552000 每个人都知道真正的答案是
  • 在 中动态添加链接样式表 [关闭]

    这个问题不太可能对任何未来的访客有帮助 它只与一个较小的地理区域 一个特定的时间点或一个非常狭窄的情况相关 通常不适用于全世界的互联网受众 为了帮助使这个问题更广泛地适用 访问帮助中心 help reopen questions 如何将链接
  • Javascript / jQuery - 转换特殊 html 字符

    我有一个pre元素中包含一些 html 代码 该代码中有特殊字符 例如 lt 所以它不会破坏页面 然后我有一个 javascript 函数 它获取此 pre 元素的内容 突出显示它 使用 codemirror 并用突出显示的文本替换元素内容
  • 从 Node.js 调用 execl、execle、execlp、execv、execvP 或 execvp 的方法

    POSIX 系统公开了一系列exec函数 允许人们将可能不同的东西加载到当前进程中 保留打开的文件描述符 进程标识符等 可以出于多种原因执行此操作 在我的情况下 这是引导 我想更改我自己的进程的命令行选项 然后在现有进程上重新加载它 这样就
  • 使用 stopPropagation() 处理 React 事件委托

    我有一个 React 项目 应该可以放置在任何网站上 我的想法是 我托管一个 javascript 文件 人们放置一个具有特定 ID 的 div 然后 React 在该 div 中进行渲染 到目前为止 除了点击事件之外 这是有效的 这些事件
  • Angular 5 中 Observable.ForkJoin 的重复 Http 请求

    我有一个 Angular 5 应用程序 组件中包含以下代码 ngOnInit Observable forkJoin this highlightedInsight this insightService getHighlightedIns
  • html5 canvas 使用图像作为蒙版

    是否可以使用具有形状的图像作为整个画布或画布内图像的蒙版 我想将图像放置在画布中 并在图像上添加蒙版 然后将其另存为新图像 您可以使用 source in globalCompositeOperation 将黑白图像用作蒙版 首先 将蒙版图

随机推荐

  • 显示和隐藏窗口,而不是在可可应用程序中关闭单击时终止应用程序

    我一直在尝试在关闭 红色按钮 单击窗口时显示隐藏窗口 我想做的是隐藏窗口 当用户再次单击我的应用程序时 它将再次显示 预先感谢所有提供答案的开发人员 我是 Cocoa 应用程序的新手 我是iOS开发人员 所以我对cocoa应用程序了解不多
  • 商店中的成功和失败函数 - Ext JS

    我有一个请求 成功后会循环遍历 JSON 响应的每个属性并将其添加到我的store var request Ext Ajax request url MCApp jsonData searchquery params start 0 lim
  • Oracle 19c 安装错误:[INS-35179] 当前可用内存小于创建 DB 所需的可用内存 (1,597MB)

    我正在尝试安装 oracle 19c 在安装过程中遇到了与内存相关的问题 INS 35179 当前可用内存小于创建 DB 所需的可用内存 6 537MB 我仔细检查了所有先决条件 例如2GB free RAM 10 GB free spac
  • 水平调整 ImageView

    我正在开发一种电子书应用程序 并尝试通过以下两种方式显示图像 当屏幕处于portrait 我将图像水平放置并垂直居中 当屏幕处于landscape 我希望图像水平填充屏幕并保持纵横比 由于我使用的图像长于宽 所以我有一个ScrollView
  • React 和 Jest:无法从测试文件中找到模块

    为目录中的 Redux 操作 App js 设置 Jest 测试 App test js app tests 这是 App js 的标头 jest unmock modules actions App js import React fro
  • 如何将具有静态值的字段添加到mongodb查找查询?

    我们可以向 mongodb 添加一些具有静态值的自定义字段吗find query 我正在尝试将 API 请求 UId 添加 附加到我们对 mongodb 进行的所有查询 以便我们可以将请求与来自 mongodb 日志的慢速查询进行映射 我在
  • H2数据库TIMESTAMP列的默认值

    我正在用 H2 数据库编写集成测试 我的数据库 生成的 初始化包括此脚本 因为生成的联接表没有此列 ALTER TABLE INT USR ADD IU INSDTTM TIMESTAMP DEFAULT NOW 这就是我创建记录的方式 I
  • C++14 元编程:在编译/初始化时自动构建类型列表

    使用 C 14 和 Curiously Recurring Template Pattern CRTP 的某种组合以及可能的Boost Hana http www boost org doc libs 1 63 0 libs hana do
  • 将 x86 与 Blazor 结合使用时“无法启动调试适配器”

    我正在尝试使用 x86 中的 ASP NET 托管 只是基本模板应用程序 来调试 Blazor WebAssembly 应用程序 如果我使用 x64 平台进行调试 应用程序可以正常运行 但是 如果我将所有项目 服务器 客户端和共享 切换到
  • Tomcat 是否使用 pl/sql 模块的缓存版本?

    好吧 想象一下这种情况 我对 pl sql 模块进行了更改 重新编译它 一切都很好 没有错误 然后 我尝试访问在 Tomcat 上运行的应用程序上的 GUI 屏幕 该屏幕调用 oracle 数据库中的 pl sql 模块 当我提交应该调用
  • 您可以更改 logback 中 %caller{0} 的输出以模仿 log4j %l 说明符吗?

    我正在从 log4j 迁移到 Logback Log4j 具有 l 格式说明符 它将打印出调用方法的完全限定名称 后跟调用者在括号之间获取文件名和行号 示例 com my company MyClass doSomething MyClas
  • 在同一域上使用 firebase 函数的 oAuth 的跨域状态 cookie 问题

    我正在为 firebase 平台的用户实现 oAuth 登录 一切正常 除非用户has 禁用跨域 cookie 这就是我所做的 从我的域 应用程序 用户被重定向到云功能 can 函数设置statecookie 并将用户重定向到 oAuth
  • 在 R 中打印小于或等号?

    我尝试使用 u2264对于小于或等号 gt names table A1 lt c x P X x P X u2264x gt print table A1 但这出现在输出中 gt x P X x P X x gt 1 2 0 562 0
  • 在 JavaScript 中从字符串生成随机数

    我想制作一个客户端 A B 测试库 每个用户都有一个存储在 cookie 中的随机数 每个测试都有一个测试名称和一系列选项 我需要一个函数 根据用户的随机数 测试名称和选项来选择随机选项 当然 该函数必须始终为给定的一组输入返回相同的选项
  • iTunesConnect Testflight 没有适用于 iOS 的版本?

    我在向我的 iOS 版本之一添加管理员时遇到问题 当我点击我的构建时 它显示我有 2 个人可以测试它 但这不是我所期待的 我期待 3 个人 因为如果我单击 iTunesConnect 用户 我会看到 3 个人 但由于某种原因 我的朋友Yu
  • jQuery 中 HTML 表单标签的有效/无效名称是什么?

    这是我在这里遇到的错误的结果jQuery form serialize 仅返回序列化表单的一个元素 https stackoverflow com questions 1290011 jquery form serialize return
  • JPA 参照完整性约束违规 oneToMany 和批量操作查询

    My domain model diagram looks like this 正如您所看到的 我在学生和出勤之间以及出勤和研讨会之间有一个一对多的关系 下面是学生类和出勤类 以及我的帮助类 初始化程序 package com semina
  • 音频编程入门[关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • MYSQL LEFT JOIN 与 GROUP BY

    我有 2 个查询 我需要加入它们 我需要将员工根据活动的工作时间与公司在规定时间段内同一活动的总工作时间进行比较 第一个查询是 SELECT u login a article p p article SUM p p going SUM p
  • 创建与时间相关的圆圈动画

    嗨 我尝试制作动画 调用函数时绘制的 3 个圆圈之一应从右向左移动 首先应在画布上绘制一个随机 黄色 蓝色或橙色 圆圈 然后在 3 秒后绘制下一个随机圆圈 然后在 2 秒后 8秒到现在为止 我怎样才能做到这一点 现在 当主循环再次开始运行时