drawImage 无法在 canvas 上工作

drawImage not working on canvas

我正在使用库 chart.js,我想画一幅图像。我设置了一些 css 来制作 canvas "responsive" 但是没有显示 img。

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:

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在canvas.

上绘制加载的图片了
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");