drawImage在canvas上不起作用

时间:2015-08-29 08:40:08

标签: javascript image canvas draw chart.js

我使用图表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网址很好。非常感谢。

1 个答案:

答案 0 :(得分: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");