gpt4 book ai didi

javascript - 图像未出现在 github 页面上

转载 作者:行者123 更新时间:2023-12-03 06:46:32 25 4
gpt4 key购买 nike

我编写了一个简单的 HTML 文件来将图像放置到 Canvas 上。它在本地主机上运行,​​但不在 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

这里有一个代码片段也不起作用:

        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");
<canvas id="vincent"></canvas>

最佳答案

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

<!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>

注意:这里我们需要一个绝对 URL,因为此示例是在 monsieurcactus.github.io/LearnElm/ 之外提供的

关于javascript - 图像未出现在 github 页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37715932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com