gpt4 book ai didi

javascript - 图片未加载到 Canvas 上?

转载 作者:行者123 更新时间:2023-11-28 06:00:35 25 4
gpt4 key购买 nike

我正在尝试将图像加载到 Canvas 上,但在尝试了所有方法后仍然无法正常工作...

Javascript:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var start = new Image();

start.onload = function(){
context.drawImage(start, 0, 0, start.width, start.height, 0, 0,
canvas.width, canvas.height);
}

start.src = "hangman0.png";

我没有发现我的代码有任何问题,因为我正在尝试绘制此图像,然后缩放到 Canvas 的宽度和高度,但无论如何图片都没有显示。任何指针?我已经尝试更改我的 HTML5 和 css 代码,但仍然无济于事。

CSS:

canvas{
background-color: rgb(0,198,255);
border-style: ridge;
border-width: 5px;
border-color: rgb(157,255,0);
position: relative;
}

HTML5:

<body>
<div id='section'>
<canvas id='myCanvas' width='979px' height='560px'></canvas>
<script src="projectJavaScript.js"></script>
</div>
</body>

在此先感谢您的帮助!

最佳答案

只要我使用 window.onload,您提供的代码就对我有效:

您是否将 script 代码包装在 window.onload 中?

<script>
window.onload=(function(){

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var start = new Image();

start.onload = function(){
context.drawImage(start, 0, 0, start.width, start.height, 0, 0,
canvas.width, canvas.height);
}

start.src = "https://dl.dropboxusercontent.com/u/139992952/multple/rainy.png";

}); // end window.onload
</script>

示例代码和演示:

注意:StackSnippets 自动将 JS 脚本代码包装在 window.onload 中

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var start = new Image();

start.onload = function(){
context.drawImage(start, 0, 0, start.width, start.height, 0, 0,
canvas.width, canvas.height);
}

start.src = "https://dl.dropboxusercontent.com/u/139992952/multple/rainy.png";
body{ background-color: ivory; }
canvas{border:1px solid red; margin:0 auto; }
<canvas id='myCanvas' width='979px' height='560px'></canvas>

关于javascript - 图片未加载到 Canvas 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36779597/

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