简体   繁体   English

为什么我的图像没有填满整个画布的宽度?

[英]Why does my image not fill the whole canvas' width?

I want my canvas to fill the whole screen width.我希望我的 canvas 填满整个屏幕宽度。 But it is not working correctly.但它不能正常工作。

 const html = document.documentElement; const canvas = document.getElementById("canvas-test"); const context = canvas.getContext("2d"); const img = new Image() img.src = "../img/runningPersonAnimation/Komp 2_00020.png"; canvas.width = window.innerWidth; canvas.height = window.innerHeight; img.onload = function() { context.drawImage(img, 0, 0); }
 .body { margin: 0; padding: 0; }
 <canvas id="canvas-test"></canvas>

As intended, my canvas fills the whole screen.正如预期的那样,我的 canvas 填满了整个屏幕。 Why is that not the case with the image?为什么图像不是这样?

How it looks at the moment:目前看起来如何: 示例图片

It may be to do with the width of the image.这可能与图像的宽度有关。 If you were to make it the full width of the canvas it would look very stretched out.如果你要把它做成 canvas 的全宽,它看起来会很拉长。 Try an image with the same dimensions as the canvas and see what it looks like.尝试与 canvas 尺寸相同的图像,看看它的外观。

The aspect ratio of the image is off, but you can use the background-image: property in CSS, the picture would look zoomed in though and perhaps a bit pixelated:图像的纵横比已关闭,但您可以使用 CSS 中的background-image:属性,虽然图片看起来会放大并且可能有点像素化:

  background-image: url('../img/yourimg.png');
  background-size: cover; /* this can be changed to percentages, such as  background-size: 50% 50%;*/
  background-position: center center;
  background-repeat: no-repeat;

Keep in mind this doesn't hold any semantic value though请记住,尽管这不具有任何语义价值

I fixed my problem by resizing the image while using drawImage.我通过在使用 drawImage 时调整图像大小来解决我的问题。

js: js:

const img = new Image()
img.src = currentFrame(20);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
img.onload=function(){
  context.drawImage(img, 0, 0, window.innerWidth, window.innerWidth * 0.66666666666); 
}

By multiplying my window.innerWidth with 0.66666666666 I get to keep my ratio, so the image does not seem stretched.通过将我的 window.innerWidth 与 0.66666666666 相乘,我可以保持我的比例,因此图像似乎不会被拉伸。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM