网站建设中canvas效果------会跳舞的机器人

本文介绍如何使用canvas实现一个会跳舞的机器人效果。通过创建robot类,定义关节和位置,设置画布配置,并结合鼠标交互,让机器人在画布上动起来。详细步骤包括构造函数、帧动画更新、画布绘制、关节和位置处理以及初始化配置。感兴趣的读者可以查看完整代码实现。
摘要由CSDN通过智能技术生成

效果预览

效果预览

创建robot类

  1. 机器人构造函数

constructor(color, light, size, x, y, struct) {
   
  this.x = x;
  this.points = [];
  this.links = [];
  this.frame = 0;
  this.dir = 1;
  this.size = size;
  this.color = Math.round(color);
  this.light = light;
  for (const p of struct.points) {
   
    this.points.push(new Robot.Point(size * p.x + x, size * p.y + y, p.f))
  }
  for (const link of struct.links) {
   
    const p0 = this.points[link.p0];
    const p1 = this.points[link.p1];
    const dx = p0.x - p1.x;
    const dy = p0.y - p1.y;
    this.links.push(new Robot.Link(this, p0, p1, Math.sqrt(dx * dx + dy * dy), link.size * size / 3, link.lum, link.force, link.disk))
  }
}
  1. 更新帧动画

update() {
   
  if (++this.frame % 20 === 0) this.dir = -this.dir;
  if (dancerDrag && this === dancerDrag && this.size < 16 && this.frame > 600) {
   
    dancerDrag = null;
    dancers.push(new Robot(this.color, this.light * 1.25, this.size * 2, pointer.x, pointer.y - 100 * this.size * 2, struct));
    dancers.sort(function(d0, d1) {
   
      return d0.size - d1.size
    })
  }
  for (const link of this.links) {
   
    const p0 = link.p0;
    const p1 = link.p1;
    const dx = p0.x - p1.x;
    const dy = p0.y - p1.y;
    const dist = Math.sqrt(dx * dx + dy * dy);
    if (dist) {
   
      const tw = p0.w + p1.w;
      const r1 = p1.w / tw;
      const r0 = p0.w / tw;
      const dz = (link.distance - dist) * link.force;
      const sx = dx / dist * dz;
      const sy = dy / dist * dz;
      p1.x -= sx * r0;
      p1.y -= sy * r0;
      p0.x += sx * r1;
      p0.y += sy * r1
    }
  }
  for (const point of this.points) {
   
    if (this === dancerDrag && point === pointDrag) {
   
      point.x += (pointer.x - point.x) * 0.1;
      point.y += (pointer.y - point.y) * 0.1
    }
    if (this !== dancerDrag) 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值