我的想法是将图像添加到 Canvas 大小并调整它的大小。然而,不知何故, Canvas 的比例比外部(HTML)大。我想它可能会大三倍。不仅如此,即使我添加了行 this.context.imageSmoothingEnabled = false;
,它也变得模糊了。
控制台也没有警告我任何东西,所以我真的不知道我做错了什么。我按照W3Schools about making game的教训和 drawImage() .
如果你们能告诉我我做错了什么以及如何解决它,那就太好了。提前致谢。
这是我的 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 调整 Canvas 大小)
<!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 图片,所以它可以有透明背景。
最佳答案
当您创建 Canvas 元素时,其默认大小为 150 CSS 像素 x 300 CSS 像素。如果使用 CSS 规则调整 Canvas 元素的大小,则“内部”大小将保持为 150*300,除非您更改属性 canvas.height
和 canvas.width
。在你的代码中是什么意思?
您的 Canvas 已被拉伸(stretch),宽度更改为窗口的 100%,“外部高度”为 500,而“内部”尺寸仍为 150x300,因此您绘制的任何内容都将以相同的方式拉伸(stretch)。
您可以查看这些相关的问答:https://stackoverflow.com/a/4939066/1919228
关于javascript - Canvas 中的图像尺寸、比例错误并且变得模糊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41823511/