簡體   English   中英

drawImage在畫布上不起作用

[英]drawImage not working on canvas

我正在使用chart.js庫,並且想繪制圖像。 我設置了一些CSS,以使畫布“響應”,但未顯示img。

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很好。 非常感謝。

加載圖像會花費一些時間,當您在當前代碼中執行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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM