图像未加载到画布上 [英] Image Not Loading on Canvas

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

问题描述

我的问题是将本地托管的图像加载到画布上时遇到问题.我曾尝试在 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:

<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 = 'imagesSelectionBagSection1LightBlue.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>

任何指导将不胜感激.

推荐答案

你离得太近了!

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

You need to put base_image.src after the base_image.onload function:

<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 = 'imagesSelectionBagSection1LightBlue.jpg';
    }
</script>

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

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