Reputation: 174
My idea was adding image to canvas size and resizing it. However, somehow, the ratio of canvas is bigger than outside (HTML). I suppose it could bigger triple times. Not only that but also it got blur even though I added the line this.context.imageSmoothingEnabled = false;
.
The console also didn't warning me anything so I really have no idea what did I wrong. I follow the lesson of W3Schools about making game and drawImage().
It would be great if you guys could tell me what did I wrong and how to fix it. Thanks in advance.
Here is the image of problem on Chrome:
Here is the image of problem on MS Edge:
Here is my JS code:
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();
}
Here is my HTML code: (I'm using CSS to resize 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>
I'm using PNG image so it could have a transparent background.
Upvotes: 2
Views: 1459
Reputation: 10342
When you create a canvas element, its default size is 150 CSS pixels by 300 CSS pixels. If your canvas element is resized using CSS rules, the "internal" size is maintained to 150*300 unless you change the attributes canvas.height
and canvas.width
. What does it mean in your code?
Your canvas has been stretched, the width changed to 100% of the window and the "external height" is 500, while the "internal" size is still 150x300, so anything you put draw will be stretched in the same way.
You can check these related Q&A: https://stackoverflow.com/a/4939066/1919228
Upvotes: 4