我的想法是将图像添加到画布大小并调整其大小。但是,以某种方式,画布的比例大于外部(HTML)。我想它可以扩大三倍。即使添加了this.context.imageSmoothingEnabled = false;线,它也变得模糊了。

控制台也没有警告我,所以我真的不知道我做错了什么。我遵循W3Schools about making gamedrawImage()的课程。

如果你们能告诉我我做错了什么以及如何解决它,那就太好了。提前致谢。

这是在Chrome上出现问题的图像:
javascript -  Canvas 中的图像尺寸,比例错误并且模糊-LMLPHP

这是MS Edge上的问题图像:
javascript -  Canvas 中的图像尺寸,比例错误并且模糊-LMLPHP

这是我的JS代码:

function startGame() {
    player = new character(document.querySelector('#eila'), 0, 0);
    playground.start();
}

var playground = {
    canvas  : document.createElement('canvas'),
    start   : function() {
        this.canvas.id = 'playground';
        this.context = this.canvas.getContext('2d');
        this.context.imageSmoothingEnabled = false;
        document.querySelector('#game').appendChild(this.canvas);

        setInterval(updatePlayground, 10)
    },
    clear   : function() {
        this.context.clearRect(0,0, this.canvas.width, this.canvas.height)
    }
}

function character(img, posX, posY) {
    this.width  = 45;
    this.height = 60;
    this.img    = img;
    this.x      = posX;
    this.y      = posY;
    this.update = function() {
        ctx = playground.context;
        ctx.drawImage(this.img, this.x, this.y, this.width, this.height)
    }
}

function updatePlayground() {
    playground.clear();
    player.update();
}


这是我的HTML代码:(我正在使用CSS调整画布的大小)

<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>Né đồ rơi</title>
    <style>
        body {
            margin: 0;
            font-family: 'Roboto', 'Open Sans'
        }

        header, #game {
            margin: auto;
            width: 55em
        }

        #game {
            background: #FAFAFA;
            border: 1px solid #EBEBEB;
            border-radius: 2px;
            padding: 1em;
        }

        #playground {
            height: 500px;
            width: 100%
        }
    </style>

    <script src='game.js'></script>
</head>
<body onload='startGame();'>
    <header>
        <p>Không được để các món đồ rơi xuống bạn!</p>
    </header>
    <section id='game'>
        <p style='text-align:center; margin-top:0'>Đã né được <span id='items'>0</span> món đồ.</p>
        <!--<canvas id='playground'></canvas>-->
    </section>
    <section style='display:none'>
        <img id='eila' src='eila.png' height='60'/>
    </section>
</body>
</html>


我正在使用PNG图片,因此它可能具有透明背景。

最佳答案

创建画布元素时,其默认大小为150 CSS像素乘300 CSS像素。如果使用CSS规则调整画布元素的大小,则除非更改属性canvas.heightcanvas.width,否则“内部”大小将保持为150 * 300。在您的代码中是什么意思?

您的画布已被拉伸,宽度更改为窗口的100%,“外部高度”为500,而“内部”尺寸仍为150x300,因此您绘制的任何内容都将以相同的方式拉伸。

您可以检查以下相关问答:https://stackoverflow.com/a/4939066/1919228

09-25 17:10
查看更多