2015-08-29 49 views
0

我正在使用庫chart.js並且要繪製圖像。我設置了一些CSS來使畫布「響應」,但img不顯示。drawImage在畫布上不起作用

CSS:

canvas{ 
    width: 100% !important; 
    height: auto !important; 
} 

帆布:

<div class="col-lg-6"> 
    <div class="content-panel"> 
    <h4><i class="fa fa-angle-right"></i> Categories</h4> 
     <div class="panel-body text-center"> 
      <canvas id="radar_best"></canvas> 
     </div> 
    </div> 
</div> 

JS:

base_image = new Image(); 
base_image.src = '../../images/no_data_graph.jpg'; 
console.log(base_image.src); 
console.log("setting image"); 
document.getElementById("radar_best").getContext("2d").drawImage(base_image, 100,100); 

的IMG URL是好的。非常感謝。

+0

當圖像準備就緒時,您只能在畫布上繪製圖像,並將該圖像放到'base_image.onload',這是一個回調函數。由於您當前的代碼不能確保在執行drawImage時加載圖像。 – fuyushimoya

回答

2

加載圖像需要時間,當您在當前代碼中執行drawImage時,如果要使用它,可能無法加載,並且會出現意外的結果。

你應該做的是使用base_image.onload,這將在圖像完全加載時調用。然後,您可以使用drawImage在畫布上繪製加載的圖像。

base_image = new Image(); 
base_image.onload = function() { 
    // When image loaded, you can then draw it on the canvas. 
    document.getElementById("radar_best").getContext("2d").drawImage(base_image, 100,100); 
}; 

base_image.onerror = function() { 
    // It's always good to have some error handling. 
    console.log('image load error'). 
    // do somthing else.... 
}; 
//always set the src after the onload callback as it is possible that image is already loaded in the browser memory hence onload event will never fire 
base_image.src = '../../images/no_data_graph.jpg'; 
console.log(base_image.src); 
console.log("setting image");