vue使用canvas实现简单动画(跳动的彩色小球)

1.新建ball.js

// 画笔
var ctx;
// 小秋数量
var size = 38;
// 画布的宽度
var w;
// 画布的高度
var h;
// 存放的小球数组
var arr = [];

function ball() {
  this.x = r(w - 160) + 60;
  this.y = r(h - 160) + 60;
  this.r = r(30) + 10;
  this.color = "#" + parseInt(Math.random() * 0xffffff).toString(16);
  this.xSpeed = r(2) + 1;
  this.ySpeed = r(2) + 1;
}
ball.prototype.show = function () {
  this.run();
  drawCircle(this.x, this.y, this.r, this.color);
};
setInterval(() => {
  ctx.clearRect(0, 0, w, h);
  for (var i = 0; i < arr.length; i++) {
    arr[i].show();
  }
}, 10);
ball.prototype.run = function () {
  if (this.x - this.r <= 0 || this.x + this.r >= w) {
    this.xSpeed = -this.xSpeed;
  }
  this.x = this.x + this.xSpeed;
  if (this.y - this.r <= 0 || this.y + this.r >= h) {
    this.ySpeed = -this.ySpeed;
  }
  this.y = this.y + this.ySpeed;
};

function drawCircle(x, y, r, color) {
  ctx.beginPath();
  ctx.arc(x, y, r, 0, Math.PI * 2);
  ctx.fillStyle = color;
  ctx.fill();
}
function r(num) {
  return parseInt(Math.random() * num);
}
function start() {
  for (var i = 0; i < size; i++) {
    var Ball = new ball();
    arr.push(Ball);
    Ball.show();
  }
}
function init(ctx1, w1, h1) {
  ctx = ctx1;
  w = w1;
  h = h1;
}

export { init, start };

2.在需要引入的ball.js

<template>
  <div class="home">
    <canvas id="canvas" />
  </div>
</template>

<script>
import { init, start } from "@/assets/ball.js";
export default {
  data() {
    return {
      ctx: {},
    };
  },
  mounted() {
    this.initCanvas();
  },
  methods: {
    initCanvas() {
      console.log("初始化canvas");
      const canvas = document.querySelector("#canvas");
      canvas.width = document.documentElement.clientWidth;
      canvas.height = document.documentElement.clientHeight;
      this.ctx = canvas.getContext("2d");
      init(this.ctx, canvas.width, canvas.height);
      start();
    },
  },
};
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值