我一直在尝试清除Javascript画布上的文本达数小时之久,但是无论如何我都无法获得可接受的解决方案。 我尝试过的事情:
我基于https://codepen.io/doms/pen/BZLezr编写了这段代码,并尝试不使用p5.js来执行此操作。无论如何,在这一点上,我感到更加烦恼的是,很难清除文本,因为我以我能想到的许多不同方式来搜索该问题,但一直未能找到解决方案。我已在下面附上我的代码以供参考。
class Particle {
constructor() {
this.x = 0;
this.y = 0;
this.speed = 1;
this.width = 30;
this.font = this.width + "px monospace"
this.residue = [];
this.reset();
}
reset() {
this.x = Math.random() * innerWidth;
this.y = (Math.random() * 10) + 10;
this.width = (Math.random() * 20) + 10;
this.font = this.width + "px monospace"
this.speed = (Math.random() * 0.8) + 0.4;
}
update() {
if (this.y > (innerHeight + this.width)) {
this.reset();
}
this.y += this.speed * 12;
}
draw() {
ctx.font = this.font;
ctx.fillStyle = "black";
for (let i = 0; i < 1; i++){
if (this.residue.length > 0){
let tempY = this.residue.pop();
let tempChar = this.residue.pop();
ctx.lineWidth = 4;
ctx.strokeStyle = "black";
ctx.strokeText(tempChar, this.x, tempY);
ctx.fillText(tempChar, this.x, tempY);
}
}
ctx.font = this.font;
ctx.fillStyle = "lime";
for (let i = 0; i < 1; i++){
let char = String.fromCharCode(Math.floor((Math.random() * 109) + 33));
this.residue.push(char);
this.residue.push(this.y);
ctx.lineWidth = 1;
ctx.fillText(char, this.x, this.y - (this.width * 0));
}
}
}
var run = true;
var particles = [];
var canvas = document.createElement('canvas');
var body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);
var ctx = canvas.getContext("2d");
canvas.width = innerWidth;
canvas.height = innerHeight;
setInterval(this.draw, 100);
function draw() {
document.body.onkeyup = function(e){
if(e.key == 'f'){
run = !run;
}
}
if (!run){
return;
}
if (particles.length < 120) {
particles.push(new Particle());
}
for (let i = 0; i < particles.length; i++){
particles[i].draw();
particles[i].update()
}
}
html, body {
margin: 0;
overflow: hidden;
}
body {
background: black;
}
input {
position: fixed;
top: 10px;
left: 10px;
}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Matrix Rain</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script src="js/index.js"></script>
</body>
</html>