2017-08-24 12 views
2

私はウェブカメラのストリームでいっぱいのキャンバスを持っています。 それに加えて、私は長方形(矩形の境界線だけ)をランダムな領域に1秒間表示したい。だから毎四角形がポップアップし、次の矩形が他の場所に表示されます。 現在、四角形が毎秒表示されていますが、最後は消えません。したがって、2秒目に2つの矩形、3つ目の3つの3つの矩形などがあります。 矩形を1秒間表示する方法、1秒後に削除する方法、または1の後に移動する方法を見つける必要があります秒:結果は私にとっては同じです。私はclearRect()を使用している場合は1秒後にキャンバスctx.rect()を非表示 - Javascript

let sx; // x axis 
let sy; // y axis 
let i = setInterval(axisChanger, 1000); // pops up every second 

function axisChanger() { 
    sx = getRandomInt(0, 535); // gets a random num 
    sy = getRandomInt(0, 445); // gets a random num 
} 

requestAnimationFrame(animate); 

function animate(t) { 
    requestAnimationFrame(animate); 
    randomRect(); 
} 

function randomRect() { 
    ctx.rect(sx, sy, 50, 30); // these 4 lines make a hollow rectangle: border only. 
    ctx.lineWidth = 2; 
    ctx.strokeStyle = '#FF0000'; 
    ctx.stroke(); 
} 

、その後、長方形の内部も消えてしまいます...そして、それにウェブカメラストリームのように一部。

答えて

2

あなただけの1つの四角形を描画する必要がある場合は、strokeRect()rect()stroke()を置き換える:

function randomRect() { 
    ctx.lineWidth = 2; 
    ctx.strokeStyle = '#FF0000'; 
    ctx.strokeRect(sx, sy, 50, 50); 
} 

現在の行動の理由はrect()がメインパスに追加し、すべてのrect()呼び出しを蓄積していることです。そのため、パスはbeginPath()を使用してクリアする必要があります。

しかし、単一の矩形しか使用していないので、パスに何も追加せずに直接レンダリングするstrokeRect()を使うことができます。

代替しかし、次のようになります。

function randomRect() { 
    ctx.beginPath();   // clear path and sub-paths 
    ctx.rect(sx, sy, 50, 30); // these 4 lines make a hollow rectangle: border only. 
    ctx.lineWidth = 2; 
    ctx.strokeStyle = '#FF0000'; 
    ctx.stroke(); 
} 
関連する問題