此问题已在此处有答案:
Canvas is stretched when using CSS but normal with width
& height
attributes(10个答案)
4天前关闭。
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>A Basic HTML5 Template</title>
<link rel="stylesheet" href="css/main-1.css">
<section id="fitting-room-section">
<canvas class="n-canvas" id="fitting-room-canvas"></canvas>
</section>
<button type="button" class="n-button">Click Me!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
</head>
<body>
<!-- your content here... -->
<script src="js/script-1.js"></script>
</body>
</html>
CSS:
.n-canvas {
width: 100%;
height: 100%;
max-width: 300px;
min-height: 400px;
background-color: red;
}
JS:
$( document ).ready(function() {
function drawImageScaled() {
let canvas = document.getElementById('fitting-room-canvas');
let ctx = canvas.getContext('2d');
let img = new Image();
img.src = 'img/bob.png';
img.onload = function(){
let imgWidth = canvas.width * (2 / 3); // Image width occupies two-thirds of the canvas width.
var ratio = imgWidth / img.width; // How much we shall shrink the image.
let imgHeight = img.height * ratio; // Shrink the image hight as much as the image width.
ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
}
}
jQuery( ".n-button" ).on( "click", drawImageScaled);
console.log( "ready!" );
});
问题
发型是扭曲的。我只是想按比例缩小它然后画出来。我的算术似乎没问题。尽我所能。
我对问题原因的推测是画布实际上是400。但在JavaScript中,它以某种方式被确定为150。这可能是导致失真的原因。
不管怎样,你能帮我吗?
1条答案
按热度按时间3bygqnnd1#
删除
max-width: 300px;
或min-height: 400px;
,并将width
和height
添加到画布附注:您的html无效。您的标签应该在
<body>
中,而不是在<head>
中