图像不会出现在github页面上

时间:2016-06-09 02:34:35

标签: javascript html github-pages

我写了一个简单的HTML文件来将图像放到画布上。它在localhost上运行,但不在github页面中运行。

图片starry-night.jpg位于同一文件夹中。

<!DOCTYPE html>
<meta charset="utf-8">
<body>

<canvas id="vincent"></canvas>

<script>

        var width  = 960;
        var height = 500;
        var canvas = document.getElementById('vincent');
        var ctx = canvas.getContext("2d");
        canvas.width  = width;
        canvas.height = height;

        var image = new Image();
        image.src= "starry-night.jpg";
        ctx.drawImage(image, 0, 0);

        console.log("done");

</script>

</body>

以下链接无效:http://monsieurcactus.github.io/LearnElm/canvas-example.html

这是一个片段也无法正常工作:

&#13;
&#13;
        var width  = 960;
        var height = 500;
        var canvas = document.getElementById('vincent');
        var ctx = canvas.getContext("2d");
        canvas.width  = width;
        canvas.height = height;

        var image = new Image();
        image.src= "http://monsieurcactus.github.io/LearnElm/starry-night.jpg";
        ctx.drawImage(image, 0, 0);

        console.log("done");
&#13;
<canvas id="vincent"></canvas>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

使用 src 属性设置图片来源会让浏览器触发获取图片的HTTP请求,而则需要等待在绘制图像之前要加载图像。像这样:

&#13;
&#13;
<!DOCTYPE html>
<meta charset="utf-8">
<body>

<canvas id="vincent"></canvas>

<script>

    var width  = 960;
    var height = 500;
    var canvas = document.getElementById('vincent');
    var ctx = canvas.getContext("2d");
    canvas.width  = width;
    canvas.height = height;

    var image = new Image();
    image.src= "http://monsieurcactus.github.io/LearnElm/starry-night.jpg";

    image.onload = function() {
         ctx.drawImage(image, 0, 0);
         console.log("done");
    }

</script>

</body>
&#13;
&#13;
&#13;

注意:这里我们需要一个绝对网址,因为此示例是在 monsieurcactus.github.io/LearnElm /

之外提供的