图像无法在画布上加载 [英] Image Not Loading on Canvas

查看:147
本文介绍了图像无法在画布上加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我在将本地托管图像加载到画布上时遇到问题。我已经尝试在Web服务器上托管代码,使用XAMPP和本地,并且LightBlue.jpg图像似乎永远不会加载。但是,当我使用网站上的外部图像时,代码可以完美运行。我在下面提供了一个示例。

My issue is that I am having problems loading locally hosted images on to the canvas. I have tried hosting the code on a web server, using XAMPP, and locally, and the LightBlue.jpg image never seems to load. However, when I use an external image from a website the code works perfectly. I have provided an example below.

HTML:

HTML:

<canvas id="Section1Canvas" width="500" height="95" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>

JAVASCRIPT:

JAVASCRIPT:

<script>
    var canvas = document.getElementById('Section1Canvas'),
    context = canvas.getContext('2d');
    make_base();
    function make_base()
    {
        base_image = new Image();
        base_image.onload = function()
        {
            context.drawImage(base_image, 10, 10);
        }
        base_image.src = 'images\Selection\Bag\Section1\LightBlue.jpg';
    }
</script>

该脚本显示在我的代码中结束HTML标记的正上方。我已经托管了我的网络服务器的所有信息,图像仍然拒绝加载。如果我使用外部图像将代码更改为以下内容,画布将完美地加载图像:

The script appears just above the closing HTML tag within my code. I have hosted all of the information my webserver and the image still refuses to load.If I were to change the code to the following using a external image the canvas loads the image perfectly:

<script>
    var canvas = document.getElementById('Section1Canvas'),
    context = canvas.getContext('2d');
    make_base();
    function make_base()
    {
        base_image = new Image();
        base_image.onload = function()
        {
            context.drawImage(base_image, 10, 10);
        }
        base_image.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
    }
</script>

任何指导都将不胜感激。

Any guidance would be greatly appreciated.

推荐答案

你太近了!

你需要把 base_image.src 放在 base_image.onload 之后:

<script>
    var canvas  = document.getElementById('Section1Canvas'),
        context = canvas.getContext('2d');
    make_base();

    function make_base()
    {
        base_image = new Image();
        base_image.onload = function()
        {
           // test that the image was loaded
           alert(base_image);  // or console.log if you prefer
           context.drawImage(base_image, 10, 10);
        }
        base_image.src = 'images\Selection\Bag\Section1\LightBlue.jpg';
    }
</script>

这篇关于图像无法在画布上加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆