html5圆的中心点,HTML5/Canvas 连接中心点

JavaScript

语言:

JaveScriptBabelCoffeeScript

确定

// canvas setup //

var w = c.width = window.innerWidth,

h = c.height = window.innerHeight,

ctx = c.getContext('2d'),

// parameters //

dotDistance = 100,

dotRadius = 5,

minProximity = dotDistance * 4,

repaintAlpha = 1,

// other values //

mouse = new Dot(w / 2, h / 2),

dots = [],

prevDD = 0, //dotDistance,

//prevDR = dotRadius,

prevMP = 0, //minProximity,

minProxSquared,

hue = 0,

templateColor = 'hsl( 0, 80%, 50% )',

// gui stuff //

params = ['dotDistance', 'dotRadius', 'minProximity', 'repaintAlpha'],

boundaries = [

[20, 200],

[2, 9],

[40, 600],

[0, 1]

],

gui = new dat.GUI({

autoPlace: false

});

// main functions //

function init() {

for (var i = 0; i < params.length; ++i)

gui.add(window, params[i], boundaries[i][0], boundaries[i][1]);

guiHolder.appendChild(gui.domElement);

considerParameters();

}

function considerParameters() {

if (dotDistance !== prevDD) {

prevDD = dotDistance;

createDots();

}

if (minProximity !== prevMP) {

prevMP = minProximity;

minProxSquared = minProximity * minProximity;

}

render();

}

function createDots() {

dots.length = 0;

for (var x = 0; x < w; x += dotDistance)

for (var y = 0; y < h; y += dotDistance)

dots.push(new Dot(x, y));

}

function updateMouse(e) {

mouse.x = e.clientX;

mouse.y = e.clientY;

hue = ((mouse.x / w + mouse.y / h) * 360) % 360;

templateColor = 'hsl( hue, 80%, brightness% )'

.replace('hue', hue);

render();

}

function render() {

ctx.fillStyle = 'rgba(0, 0, 0, alp)'

.replace('alp', repaintAlpha);

ctx.fillRect(0, 0, w, h);

dots.map(function(dot) {

dot.render();

});

}

// dot constructor //

function Dot(x, y) {

this.x = x;

this.y = y;

}

Dot.prototype.render = function() {

var dX = this.x - mouse.x, // distance X

dY = this.y - mouse.y, // distance Y

distSquared = dX * dX + dY * dY;

if (distSquared <= minProxSquared) {

var brightness = 50 - distSquared / minProxSquared * 40;

ctx.fillStyle = ctx.strokeStyle = templateColor.replace('brightness', brightness);

ctx.beginPath();

ctx.arc(this.x, this.y, dotRadius, 0, Math.PI * 2);

ctx.fill();

ctx.beginPath();

ctx.moveTo(this.x, this.y);

ctx.lineTo(mouse.x, mouse.y);

ctx.stroke();

} else {

ctx.fillStyle = '#222';

ctx.beginPath();

ctx.arc(this.x, this.y, dotRadius, 0, Math.PI * 2);

ctx.fill();

}

}

// document handlers //

window.addEventListener('mousemove', updateMouse);

guiHolder.addEventListener('mousemove', considerParameters);

window.addEventListener('resize', function() {

w = c.width = window.innerWidth;

h = c.height = window.innerHeight;

createDots();

render();

})

// blast off //

init();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值