前言

canvas是一个很神奇的玩意儿,比如画表格、画海报图都要用canvas去做,前几天有用css去做一个鼠标跟随的恶魔之眼的动画效果,想着能不能用canvas也做一个鼠标跟随的效果呢?

创建canvas画布

canvas画布创建可以直接用canvas标签即可

<canvas></canvas>

也没有过多的样式,基本都是用js去完成画布中的内容的

const canvas = document.querySelector("canvas");
let ctx = canvas.getContext("2d");

定义一个canvas 2D的画布

定义鼠标 x / y

var mouse = {
x: innerWidth / 2,
y: innerHeight / 2
};

innerWidthinnerHeight 都属于window下面的参数

初始化canvas

初始化的过程就是给canvas定义宽高,直接设置为全屏的窗口宽高即可

function init() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}

画箭头

箭头就是两条线经过旋转角度之后拼接在一起的

draw() {
const center = {
x: this.x,
y: this.y
};
const xDist = this.x - mouse.x;
const yDist = this.y - mouse.y;
const distance = Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2));
let radius = this.radius / 3 + this.radius * distance / 600;
if (radius < this.radius) {
radius = this.radius;
}
let angle, x, y;
ctx.beginPath();
angle = Math.atan2(yDist, xDist) - 90;
x = radius * Math.cos(angle) + center.x;
y = radius * Math.sin(angle) + center.y;
ctx.moveTo(x, y);
nextPoint();
ctx.lineTo(x, y);
nextPoint();
ctx.lineWidth = 1 + distance / 600 * 4;
ctx.stroke();
function nextPoint() {
angle += 1 / 3 * (2 * Math.PI);
x = radius * Math.cos(angle) + center.x;
y = radius * Math.sin(angle) + center.y;
ctx.lineTo(x, y);
}
}

nextPoint 方法就是循环画线的,通过在某个节点调用这个方法就可以循环画线

为了方便更新鼠标事件,我们可以把画线的方法放到一个 类 里面

class Arrow {
// 画线的方法
}

在初始化的时候,就可以直接调用类方法了

let arrows;
function init() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
arrows = [];
for (var x = 0; x <= canvas.width + 40; x += 40) {
for (var y = 0; y <= canvas.height + 40; y += 40) {
arrows.push(new Arrow(x, y, -20));
}
}
}

循环动画

动画就是一直更新箭头的方向,所以需要在画线的 类 里面添加一个 更新 方法用来刷新画线

class Arrow {
// 画线的方法
// 更新方法
update() {
this.draw();
}
}

添加完更新方法之后,就可以开始循环动画了

function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
arrows.forEach(Arrow => {
Arrow.update();
});
requestAnimationFrame(animate);
}

鼠标事件

鼠标在页面上随意移动时的事件方法

addEventListener("mousemove", function (event) {
mouse.x = event.clientX;
mouse.y = event.clientY;
});

监听窗口大小,便于修改canvas的宽度和更新初始化方法

addEventListener("resize", function () {
canvas.width = innerWidth;
canvas.height = innerHeight;
init();
});

还可以加上移动端上的 touch 事件

document.addEventListener("touchstart", function (e) {
e.preventDefault();
mouse.x = e.targetTouches[0].clientX;
mouse.y = e.targetTouches[0].clientY;
});
document.addEventListener("touchmove", function (e) {
e.preventDefault();
mouse.x = e.targetTouches[0].clientX;
mouse.y = e.targetTouches[0].clientY;
});

实现效果

JavaScript利用canvas实现鼠标跟随特效

以上就是JavaScript利用canvas实现鼠标跟随特效的详细内容,更多关于JavaScript canvas鼠标跟随特效的资料请关注本站其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。