简体   繁体   English

drawImage在画布上不起作用

[英]drawImage not working on canvas

I'm using the library chart.js and I want to draw an image. 我正在使用chart.js库,并且想绘制图像。 I set some css to make the canvas "responsive" but the img isn't displayed. 我设置了一些CSS,以使画布“响应”,但未显示img。

css: CSS:

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

Canvas: 帆布:

<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: 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);

The img URL is fine. img URL很好。 Thanks a lot. 非常感谢。

Load an image takes time, when you execute the drawImage in your current code, it may not loaded when you want to use it, and that would comes out an unexpected result. 加载图像会花费一些时间,当您在当前代码中执行drawImage时,如果要使用它,则可能不会加载该图像,这会导致意外结果。

What you should do is use base_image.onload , which will be called when image is fully loaded. 您应该使用base_image.onload ,当图像完全加载时将调用它。 Then you can use drawImage to draw the loaded image on the canvas. 然后,您可以使用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