我正在尝试在HTML5画布中显示背景图像。我已确保图像和html文件在同一文件夹中,因此图像正在显示。我还试图调整图像的大小,以确保图像对于画布来说不会太大,但是,图像一直显示在画布下,而不是画布内部。我的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Opening screen</title>
</head>
<body>
<img>
<canvas id="canvas"
style =
"width: 700px;
height: 500px;
border: 1px solid #000000;
padding-left: 0;
padding-right: 0;
margin-top: 40px;
margin-left: auto;
margin-right: auto;
display: block;">
</canvas>
<img id="sky" src="sky.png">
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("sky");
ctx.drawImage(img, 10, 10);
</script>
</body>
</html>
发布于 2019-01-02 10:46:33
你可以移除你的img标签,并为你的画布设置背景
<canvas id="canvas"
style =
"width: 700px;
background: url(https://placekitten.com/1000/1000) no-repeat top center;
background-size:cover;
height: 500px;
border: 1px solid #000000;
padding-left: 0;
padding-right: 0;
margin-top: 40px;
margin-left: auto;
margin-right: auto;
display: block;">
</canvas>
发布于 2019-01-02 10:43:09
当您尝试将图像插入画布时,图像尚未加载/下载。
您可以将代码添加到window.onload
函数中,它应该可以工作
window.onload = function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("sky");
ctx.drawImage(img, 10, 10);
}
至于为什么它显示在画布下面,您有一个img
元素,其中包含该图像,放置在画布之后。
发布于 2019-01-02 10:41:59
将其添加到脚本中-在加载图像后将其绘制到画布上。
var background = new Image();
background.src = "www.xyz.com/background.png";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
https://stackoverflow.com/questions/54004810
复制