【发布时间】:2020-04-23 08:55:59
【问题描述】:
我正在使用此代码为我的学校 webdev 课程完成一个项目。我一直盯着这个几个小时尝试不同的东西,看不出我哪里出错了。这里的任何帮助都会很热门。
//Initial Setup
var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d');
canvas.width = innerWidth;
canvas.height = innerHeight;
//Variables
const mouse = {
x: innerWidth / 2,
y: innerHeight / 2
};
const colors = ['#2185C5', '#7ECEFD', '#FFF6E5', '#FF7F66'];
// Event Listeners
addEventListener('mousemove', event => {
mouse.x = event.clientX;
mouse.y = event.clientY;
});
addEventListener('resize', () => {
canvas.width = innerWidth
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)];
}
// Objects
function Particle(x, y, radius, color) {
this.x = x
this.y = y
this.radius = radius
this.color = color;
this.radians = Math.random() * Math.PI * 2;
this.velocity = 0.05;
this.distanceFromCenter = randomIntFromRange(50, 120);
this.lastMouse = {x: x, y: y};
this.update = () => {
const lastPoint = {x: this.x, y: this.y};
//move points over time
this.radians += this.velocity;
//Drag Effect
this.lastMouse.x += (mouse.x - this.lastMouse.x) * 0.05;
this.lastMouse.y += (mouse.y - this.lastMouse.y) * 0.05;
//Circuler Motion
this.x = this.lastMouse.x + Math.cos(this.radians) * this.distanceFromCenter;
this.y = this.lastMouse.y + Math.sin(this.radians) * this.distanceFromCenter;
this.draw(lastPoint);
};
}
this.draw = lastPoint => {
c.beginPath();
c.strokestyle = this.color;
c.lineWidth = this.radius;
c.moveTo(lastPoint.x, lastPoint.y);
c.lineTo(this.x, this.y);
c.stroke();
c.closePath();
}
// Implementation
let particles;
function init() {
particles = []
for (let i = 0; i < 10; i++) {
const radius = (Math.random() * 2) + 1;
particles.push(new Particle(canvas.width / 2, canvas.height / 2, radius, randomColor(colors)));
}
}
// Animation Loop
function animate() {
requestAnimationFrame(animate);
c.fillstyle = 'rgba (255, 255, 255, 0.05)';
c.fillRect(0, 0, canvas.width, canvas.height)
particles.forEach(particle => {
particle.update();
})
}
init();
animate();
我一直遇到...“未捕获的 TypeError:this.draw 不是函数”的错误。我一直在绞尽脑汁试图完成这项工作。有人可以再看看这个以减轻压力吗?谢谢!
这是我运行 JS 的 HTML。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TEST</title>
<style type="text/css">
canvas {
border: 1px solid black;
}
body {
margin: 0;
}
</style>
</head>
<body>
<canvas></canvas>
<script src="java/project.js"></script>
</body>
</html>
【问题讨论】:
标签: javascript