【发布时间】:2017-06-08 23:25:14
【问题描述】:
我的想法是将图像添加到画布大小并调整其大小。但是,不知何故,画布的比例大于外部(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 调整画布大小)
<!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 图像,因此它可以具有透明背景。
【问题讨论】:
-
我没有在您的代码中看到调整大小。注意:
clearRect不调整大小画布。为了调整大小,您必须使用 canvas element 的width/height属性。 -
啊,抱歉,我使用 CSS 代码调整画布大小。我马上更新。
标签: javascript html canvas drawimage