1 回答
TA贡献1852条经验 获得超1个赞
我无法从你的代码中得到太多,最终重构了所有。
希望这能让您走上正确的方向
class Text {
constructor(txt, font, backColor, textColor, x, y, speed) {
this.txt = txt;
this.font = font;
this.backColor = backColor;
this.textColor = textColor;
this.initX = x;
this.x = x;
this.y = y;
this.speed = speed;
}
draw(ctx) {
ctx.beginPath()
ctx.font = this.font;
ctx.textBaseline = "top";
ctx.fillStyle = this.backColor;
var width = ctx.measureText(this.txt).width;
ctx.fillRect(this.x, this.y, width, parseInt(this.font, 10));
ctx.fillStyle = this.textColor;
ctx.fillText(this.txt, this.x, this.y);
this.x -= this.speed ;
if (this.x < -width)
this.x = this.initX
}
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
initX = canvas.width
dogs = new Text("Dogs are cute animals", "20px Arial", "#f50", "#000", initX, 20, 1)
cats = new Text("Cats say Miauu", "22px Arial", "#000", "#0F0", initX, 50, 0.5)
hello = new Text("HELLO", "12px Arial", "#F00", "#FF0", initX, 80, 3)
setInterval(draw, 20)
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
dogs.draw(ctx)
cats.draw(ctx)
hello.draw(ctx)
}
<canvas id="canvas" width=220 height=100></canvas>
应该都清楚了,如果有什么让你困惑的请告诉我
- 1 回答
- 0 关注
- 71 浏览
添加回答
举报