如何避免在 html5 canvas 内拉伸图像

问题描述 投票:0回答:1

画布占据了屏幕上的所有可用空间,我用它来渲染网站的背景。

        canvas {
            position: absolute;
            width:100%;
            height:100%;
            image-rendering: pixelated;
        }

我正在通过

ctx.drawImage(img, 0,0)
绘制图像,我需要它根据其原始分辨率保持原始尺寸,无论画布本身的尺寸是多少。

我尝试对画布本身进行缩放,但没有成功。

javascript html html5-canvas
1个回答
0
投票

看起来你在绘制图像时需要指定图像的宽度和高度。您可以通过提供宽度和高度作为参数来做到这一点:

 ctx.drawImage(img, 0,0, imageWidth, imageHeight)

文档有:

drawImage(image, dx, dy, dWidth, dHeight)

您可以查看图像文件属性来确定其尺寸

MDN 文档-drawImage

© www.soinside.com 2019 - 2024. All rights reserved.