2014-12-04 33 views
1

我使用PNG作爲HTML5 Canvas中充當音頻可視化工具的一系列矩形的背景圖案,但是,我正在接收Uncaught TypeError代碼:無法在'CanvasRenderingContext2D'上執行'createPattern'

HTML:

<canvas id="analyser_render"></canvas> 

JS:

canvas = document.getElementById('analyser_render'); 
ctx = canvas.getContext('2d'); 

ctx.clearRect(0, 0, canvas.width, canvas.height); 
pattern = ctx.createPattern("images/analyser.png", "repeat-x"); 
ctx.fillStyle = pattern; 

bars = 30; 
for (var i = 0; i < bars; i++) { 
    bar_x = i * 10; 
    bar_width = 9; 
    bar_height = -(dataArray[i]/2); 
    ctx.fillRect(bar_x, canvas.height, bar_width, bar_height); 
} 

這是我的實際代碼僅一部分,其包括矩形的創建的部分。 dataArray變量是Web Audio API的一部分,不屬於相關問題的一部分。

回答

-1

對於要正確加載的圖像,您需要創建一個圖像對象,然後設置其來源。

img = new Image(); 
img.src = 'images/analyser.png'; 

然後在createPattern,調用圖像對象

pattern = ctx.createPattern(img, "repeat-x"); 
+1

正確加載,你還需要使用'onload'回調映像加載是異步的圖像。 – K3N 2014-12-04 15:58:42

+0

不一定@KenFyrstenberg,我只是把上面的代碼放到我的函數中,並且按照我希望的方式工作,沒有任何onload。然後再次,img聲明在INIT函數中,而createPattern在循環的requestAnimationFrame函數中。所以可能存在混淆。 – Murphy1976 2014-12-04 16:14:14

+1

這是因爲圖像緩存在瀏覽器中並在本地加載。當您將此代碼在線並且用戶在第一次加載圖像時可能會或可能不會及時加載圖像。這就是爲什麼onload *必須正確處理的原因。 – K3N 2014-12-04 16:28:34