Mouse Pen
by vovkasolovev
HTML
<canvas id="mousepen"></canvas>
<div id="labelDiv">Link to <a href="http://podhod.ru" target="_blank">PODHOD</a></div>
CSS
:root {
--color-1: #ff77ff;
}
body, html {
padding: 0;
margin: 0;
background: #f0f0f0;
}
canvas#mousepen {
mix-blend-mode: multiply;
position: absolute;
top: 0px;
left: 0px;
z-index: 999999999;
pointer-events:none;
}
#labelDiv {
font-size: 70px;
position: absolute;
top: 100px;
left: 300px;
z-index: 1;
}
JavaScript
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext('2d');
// for intro motion
let mouseMoved = false;
let mouse = {
x: .5 * window.innerWidth,
y: .5 * window.innerHeight,
tX: 0,
tY: 0
}
let params = {
pointsNumber: 22,
widthFactor: 0.2,
mouseThreshold: 0.8,
spring: 0.4,
friction: 0.5,
opacity: 1,
default_color: "#0077ff",
color: getComputedStyle(document.documentElement).getPropertyValue('--color-1')
};
const touchTrail = new Array(params.pointsNumber);
for (let i = 0; i < params.pointsNumber; i++) {
touchTrail[i] = {
x: mouse.x,
y: mouse.y,
vx: 0,
vy: 0,
}
}
window.addEventListener("click", e => {
updateMousePosition(e.pageX, e.pageY);
});
window.addEventListener("mousemove", e => {
mouseMoved = true;
updateMousePosition(e.pageX, e.pageY);
});
window.addEventListener("touchmove", e => {
mouseMoved = true;
updateMousePosition(e.targetTouches[0].pageX, e.targetTouches[0].pageY);
});
function updateMousePosition(eX, eY) {
mouse.tX = eX;
mouse.tY = eY;
}
setupCanvas();
updateBubbles(0);
window.addEventListener('resize', () => {
setupCanvas();
});
function updateBubbles(t) {
// for intro motion
if (!mouseMoved) {
ctx.globalAlpha = 0;
mouse.tX = (.5 + .3 * Math.cos(.002 * t) * (Math.sin(.005 * t))) * window.innerWidth;
mouse.tY = (.5 + .2 * (Math.cos(.005 * t)) + .1 * Math.cos(.01 * t)) * window.innerHeight;
} else {
ctx.globalAlpha = params.opacity;
};
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
touchTrail.forEach((p, pIdx) => {
if (pIdx === 0) {
p.x = mouse.x;
p.y = mouse.y;
ctx.moveTo(p.x, p.y);
} else {
p.vx += (touchTrail[pIdx - 1].x - p.x) * params.spring;
p.vy += (touchTrail[pIdx - 1].y - p.y) * params.spring;
p.vx *= params.friction;
...