html 空间扭曲效果,HTML5 Canvas点阵空间塌缩交互动画

JavaScript

语言:

JaveScriptBabelCoffeeScript

确定

var canvas = document.querySelector("canvas");

var c = canvas.getContext("2d");

var w = (canvas.width = innerWidth);

var h = (canvas.height = innerHeight);

// Variables

var mouse = {

x: undefined,

y: undefined

};

var colors = [

"#0082C4",

"#00E271",

"#FFE451",

"#E21B75",

"#F27426"

];

// Event Listeners

addEventListener("mousemove", function(event) {

mouse.x = event.clientX;

mouse.y = event.clientY;

});

addEventListener("resize", function() {

w = canvas.width = innerWidth;

h = canvas.height = innerHeight;

init();

});

// Utility Functions

function randomIntFromRange(min, max) {

return Math.floor(Math.random() * (max - min + 1) + min);

}

function randomColor(colors) {

return colors[Math.floor(Math.random() * colors.length)];

}

function Dot(x, y, color) {

this.x = x;

this.y = y;

this.dx = x;

this.dy = y;

this.color = color;

this.radius = 6;

// this.distanceFromCenter = randomIntFromRange(50, 120);

}

Dot.prototype.update = function() {

var rad = 50;

var disX = mouse.x - this.x;

var disY = mouse.y - this.y;

var ds = Math.sqrt(disX * disX + disY * disY);

var angle = Math.atan2(disY, disX) ;

// var dist = rad / ds;

if (ds < rad) {

this.x += Math.cos(angle) * ds * 0.1;

this.y += Math.sin(angle) * ds * 0.1;

}

this.draw();

};

Dot.prototype.draw = function() {

c.beginPath();

c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);

c.fillStyle = this.color;

c.fill();

c.closePath();

};

var dots = [];

var spacing = 20;

function init() {

dots = [];

for (var x = spacing / 2; x < w; x += spacing) {

for (var y = spacing / 2; y < h; y += spacing) {

var color = randomColor(colors);

var dot = new Dot(x, y, color);

dots.push(dot);

dot.draw();

}

}

}

function animate() {

c.clearRect(0, 0, canvas.width, canvas.height);

dots.forEach(dot => {

dot.update();

});

requestAnimationFrame(animate);

}

init();

animate();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值