所以,我有一条线在改变颜色的同时从我的边框墙反弹。但是现在我必须创建第二条白线,它将在第一行擦除之后的3或4秒内完成。所以它只有4秒长的颜色线从墙壁反弹。我不知道该怎么做。我已经尝试过使用setTimeout,创建多个函数等。
var ctx=document.getElementById("canvas1").getContext("2d");
ctx.strokeStyle="red";
ctx.lineWidth=1;
var x=0
var y=0
var dx=1
var dy=1
function rysuj(){
ctx.strokeStyle="#"+((1<<24)*Math.random()|0).toString(16);
ctx.beginPath()
ctx.moveTo(x,y);
ctx.lineTo(x+dx,y+dy);
ctx.stroke();
if(x>200||x<0) dx=-dx;
if(y>150||y<0) dy=-dy;
x=x+dx;
y=y+dy;
}
setInterval ('rysuj()', 5);
<canvas id="canvas1" style="width:1000px; height:500px; border-style:solid;">
</canvas>
答案 0 :(得分:0)
看起来关键是要有两个绘图功能(注意,这不是理想的,但它有效)并且总是有&#34; white&#34;函数显式设置strokeStyle。这是因为两个绘制函数的上下文都是从同一个画布中检索的,除非你在&#34; white&#34;上显式设置它。绘制,它将是前一个&#34;红色&#34;画。
见下文:
var getCanvasContext = function(strokeColor) {
var ctx = document.getElementById("canvas1").getContext("2d");
ctx.strokeStyle=strokeColor;
ctx.lineWidth=1;
return {ctx: ctx, x: 0, y:0, dx:1, dy:1, change: strokeColor !== "white"};
}
var drawRed = function(canvasContext) {
var ctx = canvasContext.ctx,
x = canvasContext.x,
y = canvasContext.y,
dx = canvasContext.dx,
dy = canvasContext.dy;
if (canvasContext.change) {
ctx.strokeStyle="#"+((1<<24)*Math.random()|0).toString(16);
}
ctx.beginPath();
ctx.moveTo(x,y);
ctx.lineTo(x+dx, y+dy);
ctx.stroke();
if(x>200||x<0) dx=-dx;
if(y>150||y<0) dy=-dy;
x=x+dx;
y=y+dy;
canvasContext.ctx = ctx;
canvasContext.x = x;
canvasContext.y = y;
canvasContext.dx = dx;
canvasContext.dy = dy;
};
var drawWhite = function(canvasContext) {
var ctx = canvasContext.ctx,
x = canvasContext.x,
y = canvasContext.y,
dx = canvasContext.dx,
dy = canvasContext.dy;
ctx.strokeStyle="#ffffff";
ctx.beginPath();
ctx.moveTo(x,y);
ctx.lineTo(x+dx, y+dy);
ctx.stroke();
if(x>200||x<0) dx=-dx;
if(y>150||y<0) dy=-dy;
x=x+dx;
y=y+dy;
canvasContext.ctx = ctx;
canvasContext.x = x;
canvasContext.y = y;
canvasContext.dx = dx;
canvasContext.dy = dy;
};
var redContext = getCanvasContext("red");
var whiteContext = getCanvasContext("white");
setInterval(function() {
drawRed(redContext);
}, 5);
setTimeout(function() {
setInterval(function() {
drawWhite(whiteContext)
}, 5);
}, 4000);
希望这会有所帮助(见小提琴:JSFiddle Link)