canvas雙緩存繪製中,緩存canvas中繪製的圖片無法在顯示canvas中顯示出來

問題1:在canvas動畫的繪製過程中,ctx.clearRect()與ctx的再次重繪會出現一個顯示閃爍問題

原因:這是由於清空canvas後,出現了一個繪製過程的空檔期。

解決方法:引出了雙緩存方式的繪製方法。相應代碼如下:

function updateCanvas(){
    var canvas = document.getElementById('canvas'); // 獲取頁面中的 canvas
    var ctx = canvas.getContext('2d');
     
    var tempCanvas = document.createElement('canvas'); // 新建一個緩存 canvas
    var tempCtx = tempCanvas.getContext('2d');
    tempCanvas.width = 1440; 
    tempCanvas.height = 417; 
 
    // 開始繪製
    tempCtx.drawImage(img,0,0); // 背景
    ... // 省略其他繪製過程
     
    // 緩存 canvas 繪製完成
     
    ctx.clearRect(0,0,1440,417); // 清空舊 canvas
    ctx.drawImage(tempCanvas,0,0); // 將緩存 canvas 複製到舊的 canvas
}

 

問題2:在使用雙緩存方式過程中,我是加載的本地圖片,出現了tempCanvas中繪製的圖片無法在顯示canvas中顯示出來

問題代碼:

function updateCanvas(){
    const canvas = document.getElementById('canvas'); // 獲取頁面中的 canvas
    const ctx = canvas.getContext('2d');
     
    const tempCanvas = document.createElement('canvas'); // 新建一個緩存 canvas
    const tempCtx = tempCanvas.getContext('2d');
    tempCanvas.width = 1440; 
    tempCanvas.height = 417; // 設置寬高
 
    // 開始繪製
    var img = new Image();
    img.src = "./img/bg.jpg";
    img.onload = function(){
        tempCtx.drawImage(img,0,0); // 背景
    }
    // 緩存 canvas 繪製完成
     
    ctx.clearRect(0,0,1440,417); // 清空舊 canvas
    ctx.drawImage(tempCanvas,0,0); // 將緩存 canvas 複製到舊的 canvas
}

原因:在將緩存canvas繪製到顯示canvas的時候,由於圖片加載未完成,故此tempCtx還未將圖片繪製到自己的canvas中去,便導致了顯示canvas中沒有繪製出圖片。

解決方法:將ctx.clearRect()以及ctx.drawImage()放到img.onload()中。

function updateCanvas(){
    const canvas = document.getElementById('canvas'); // 獲取頁面中的 canvas
    const ctx = canvas.getContext('2d');
     
    const tempCanvas = document.createElement('canvas'); // 新建一個緩存 canvas
    const tempCtx = tempCanvas.getContext('2d');
    tempCanvas.width = 1440; 
    tempCanvas.height = 417; // 設置寬高
 
    // 開始繪製
    var img = new Image();
    img.src = "./img/bg.jpg";
    img.onload = function(){
        tempCtx.drawImage(img,0,0); // 背景
        // 緩存 canvas 繪製完成
        ctx.clearRect(0,0,1440,417); // 清空舊 canvas
        ctx.drawImage(tempCanvas,0,0); // 將緩存 canvas 複製到舊的 canvas
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章