2016-01-02 64 views
0

我想要移動剪輯區域的位置,然後在剪輯區域中繪製。下面的方法怎麼不起作用? 感謝任何啓示:-) 傑拉德是否可以爲畫布剪輯區域的位置設置動畫?

<canvas id="canvas" width="150" height="150"></canvas> 
<script> 

function fade() { 
    var level = 0; 
    var xClip=0, yClip=0; 
    var step = function () { 
     var ctx = document.getElementById('canvas').getContext('2d'); 
     ctx.fillRect(0,0,150,150); 

     // Create a circular clipping path 
     ctx.beginPath(); 
     ctx.arc(xClip, xClip, 60, 0, Math.PI*2, true); 
     ctx.clip(); 

     // draw background 
     var lingrad = ctx.createLinearGradient(0,-75,0,75); 
     lingrad.addColorStop(0, '#232256'); 
     lingrad.addColorStop(1, '#143778'); 

     ctx.fillStyle = lingrad; 
     ctx.fillRect(-75,-75,150,150); 

     if (level < 15) { 
      level ++; 
      xClip = yClip = level*10; 
      console.log("level: " + level); 
      console.log("xClip: " + xClip); 
      setTimeout(step, 1000); 
     } 
    }; 
    setTimeout(step,100); 
} 
fade(); 
</script> 

+2

您只需創建一次上下文。使用'ctx.save()'在創建clop之前保存上下文狀態,然後使用函數底部的'ctx.restore()'恢復狀態。 – Blindman67

回答

0

動畫剪輯。

當您多次應用剪輯時,剪輯區域被剪輯到現有剪輯。在不考慮此情況下動畫剪輯區域將創建一個更小的剪輯區域。

保存和恢復。

動畫剪輯區域時,您需要保存和恢復畫布狀態。 ctx.save()將當前畫布2D狀態保存到堆棧,ctx.restore()從堆棧頂部彈出最後保存的狀態。保存和恢復可以嵌套。每次保存都必須在某一時刻進行恢復,否則最終會咀嚼內存並最終溢出狀態堆棧。

修復您的代碼。

你的代碼幾乎就在那裏,只需要做一些修改就可以做你想做的事。我也將canvas.getContext()移出了淡入淡出的功能,因爲您只需要這樣做一次。

function fade() { 
    var level = 0; 
    var xClip=0, yClip=0; 
    var step = function () { 
     ctx.fillRect(0,0,150,150); 

     //--------------------------------------------- 
     ctx.save(); // push the current unclipped state to the state stack. 

     // Create a circular clipping path 
     ctx.beginPath(); 
     ctx.arc(xClip, xClip, 60, 0, Math.PI*2, true); 
     ctx.clip(); 

     ctx.fillStyle = lingrad; 
     ctx.fillRect(-75,-75,150,150); 

     if (level < 15) { 
      level ++; 
      xClip = yClip = level*10; 
      setTimeout(step, 1000); 
     } 

     //--------------------------------------------- 
     ctx.restore(); // pop the last saved state from the state stack 
         // restoring the clip region to the default 
         // ready for the next call to step. 

    }; 
    setTimeout(step,100); 
} 

// get the 2D context only once 
var ctx = document.getElementById('canvas').getContext('2d'); 

// As the gradient does not change over time don't create this every 
// frame as it is a expensive operation 
var lingrad = ctx.createLinearGradient(0,-75,0,75); 
lingrad.addColorStop(0, '#232256'); 
lingrad.addColorStop(1, '#143778'); 

fade(); 
+0

我知道我們不應該在評論中表示感謝(有什麼方法可以這麼做?)但我必須 - 非常感謝:-) – Gerard

+0

@Gerard感謝您的感謝。批准的方式是隻選擇回答的答案或進行投票,但感謝就好。很高興幫助。 – Blindman67