javascript – HTML画布在画布下方而不是在画布内显示图像
作者:互联网
我试图在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>
解决方法:
你可以删除你的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>
标签:html,javascript,canvas,background-image 来源: https://codeday.me/bug/20190727/1548961.html