2017-05-14 130 views
0

什麼?我正在嘗試使用畫布和JavaScript在網格上顯示一個動畫,該動畫也必須使用JavaScript繪製。 https://jsfiddle.net/cp1wqeeg/6/雪碧動畫clearRect替代?

問題!要刪除動畫的前一幀,我使用了clearRect()。然而,這打破了我的網格,我不想:(

的jsfiddle:https://jsfiddle.net/cp1wqeeg/5

ctx.clearRect(50, 100, width, height);

問題我如何刪除我的動畫的前一幀沒有打破電網我身後的精靈?

+0

我相信你將不得不清除一切,然後重新繪製網格 – BenShelton

回答

0

這裏的常見操作是清除所有內容並重新繪製所有內容
但是,如果在您的ca中可能會變得很麻煩se,你的背景不會改變。

在這種情況下,一個簡單的解決方案是使用屏幕畫布,它將作爲圖層。

首先,您在初始階段在此屏幕畫布上繪製網格。
然後在您的循環中,您只需在主環境中使用drawImage方法繪製脫機畫布。

var canvas = document.getElementById("myCanvas"), 
 
ctx = canvas.getContext("2d"), 
 

 
fov = 300, 
 
viewDist = 5, 
 
w = canvas.width/2, 
 
h = canvas.height/2, 
 
// here we create an offscreen canvas for the grid only 
 
gridCtx = canvas.cloneNode().getContext('2d'), 
 
angle = 0, 
 
i, p1, p2, 
 
grid = 5; 
 

 
function initGrid(){ 
 
/// create vertical lines on the off-screen canvas 
 
for(i = -grid; i <= grid; i++) { 
 
    p1 = rotateX(i, -grid); 
 
    p2 = rotateX(i, grid); 
 
    gridCtx.moveTo(p1[0], p1[1]); 
 
    gridCtx.lineTo(p2[0], p2[1]); 
 
    i++; 
 
} 
 
/// create horizontal lines 
 
for(i = -grid; i <= grid; i++) { 
 
    p1 = rotateX(-grid, i); 
 
    p2 = rotateX(grid, i); 
 
    gridCtx.moveTo(p1[0], p1[1]); 
 
    gridCtx.lineTo(p2[0], p2[1]); 
 
} 
 
gridCtx.stroke(); 
 
} 
 

 
function rotateX(x, y) { 
 
    var rd, ca, sa, ry, rz, f; 
 
    rd = angle * Math.PI/180; 
 
    ca = Math.cos(rd); 
 
    sa = Math.sin(rd); 
 

 
    ry = y * ca; 
 
    rz = y * sa; 
 

 
    f = fov/(viewDist + rz); 
 
    x = x * f + w; 
 
    y = ry * f + h; 
 

 
    return [x, y]; 
 
} \t 
 

 
initGrid(); 
 
var width = 200, 
 
height = 200, 
 
frames = 2, 
 
currentFrame = 0,  
 
\t 
 
imageSprite = new Image() 
 
imageSprite.src = 'https://s27.postimg.org/eg1cjz6cz/sprite.png'; 
 
\t 
 
var drawSprite = function(){ 
 
\t \t ctx.clearRect(0,0,canvas.width, canvas.height); 
 
    ctx.drawImage(gridCtx.canvas, 0,0); // now draw our grid canvas 
 
\t \t ctx.drawImage(imageSprite, 0, height * currentFrame, width, height, 50, 100, width, height); 
 
\t \t 
 
\t \t if (currentFrame == frames) { 
 
\t \t currentFrame = 0; 
 
\t \t } else { 
 
\t \t currentFrame++; 
 
\t \t } 
 
} 
 
setInterval(drawSprite, 500);
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #c3c3c3;"></canvas>

+0

謝謝。這可以做到這一點,但我的實際場景中有更多的圖像,這就造成了網格問題 - 它被繪製在其他圖像上。爲了解決這個問題,我爲網格創建了第二個畫布DOM,並相應地應用了z-index值。 https://jsfiddle.net/cp1wqeeg/8/ – Eelmaster