【发布时间】:2022-03-31 01:27:28
【问题描述】:
我在背景图片上放置了一个画布。当我按下“试一试”按钮时,图像出现在画布中,但它的大小与父级不同或不适合画布。我只看到图片的左上角。
父图像和画布大小相同。
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div class="bg">
<img src="Assets/Images/background.png" alt="background">
</div>
<section class="content">
<p>Image to use:</p>
<img id="taxi" src="Assets/Images/PV.png" width="250" height="300">
<p>Canvas to fill:</p>
<canvas id="myCanvas" width="250" height="300"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<p><button onclick="myCanvas()">Try it</button></p>
</section>
</body>
</html>
JS
function myCanvas() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("taxi");
ctx.drawImage(img,10,10);
}
我如何获得它以使画布中的图像与父图像大小相同? 另外,当我在第二次按下“Try It”时,如何让图像从画布上消失?
【问题讨论】:
-
在
myCanvas尝试ctx.drawImage(img,0,0);。如果你这样做ctx.drawImage(img,10,10),这将使你的图像在 x 方向偏移 10 px,在 y 方向偏移 10 px -
您希望画布具有相同的比例等,对吧?
标签: javascript html canvas