网站动态背景线条跟随鼠标移动,吸附鼠标效果
动态背景线条,鼠标移动可以吸附,可以添加配置,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>粒子线条canvas效果</title>
<style>
#J_dotLine {
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="J_dotLine"></canvas>
<script>
; (function (window) {
function Dotline(option) {
this.opt = this.extend({
dom: 'J_dotLine',//画布id
cw: 1000,//画布宽
ch: 500,//画布高
ds: 100,//点的个数
r: 0.5,//圆点半径
cl: '#000',//颜色
dis: 100//触发连线的距离
}, option);
this.c = document.getElementById(this.opt.dom);//canvas元素id
this.ctx = this.c.getContext('2d');
this.c.width = this.opt.cw;//canvas宽
this.c.height = this.opt.ch;//canvas高
this.dotSum = this.opt.ds;//点的数量
this.radius = this.opt.r;//圆点的半径
this.disMax = this.opt.dis * this.opt.dis;//点与点触发连线的间距
this.color = this.color2rgb(this.opt.cl);//设置粒子线颜色
this.dots = [];
//requestAnimationFrame控制canvas动画
var RAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
var _self = this;
//增加鼠标效果
var mousedot = {
x: null, y: null, label: 'mouse' };
this.c.onmousemove = function (e) {
var e = e || window.event;
mousedot.x = e.clientX - _self.c.offsetLeft;
mousedot.y = e.clientY - _self.c.offsetTop;
};
this.c.onmouseout = function (e) {
mousedot.x = null;
mousedot.y = null;
}
//控制动画
this.animate = function () {
_self.ctx.clearRect(0, 0, _self.c.width, _self.c.height);
_self.drawLine([mousedot].concat(_self.dots));
RAF(_self.animate);
};
}
//合并配置项,es6直接使用obj.assign();
Dotline.prototype.extend = function (o, e) {
for (var key in e) {
if (e[key]) {
o[key] = e[key]
}
}
return o;
};
Dotline.prototype.color2rgb =