Reputation: 25
I can't figure out how to change the format of an image. I'm trying to make the Dino Game from Google Chrome. And changing the image size won't work.
My code:
window.onload = function() {
var cvs = document.getElementById("gameArea");
var ctx = cvs.getContext("2d");
var dino;
var obst = [];
function drawDino() {
var dinoImg = new Image();
dinoImg.src = 'dino.png';
dinoImg.onload = function() {
ctx.drawImage(dinoImg, 0, 0);
this.style.width = 100;
this.style.height = 100;
}
}
function drawObst() {
}
function draw() {
drawDino();
drawObst();
}
function startGame() {
setInterval(draw,50);
}
startGame();
}
Upvotes: 2
Views: 74
Reputation: 386600
Use the parameters of drawImage
for resizing the image.
void ctx.drawImage(image, dx, dy, dWidth, dHeight);
window.onload = function() {
var cvs = document.getElementById("gameArea");
var ctx = cvs.getContext("2d");
var dino;
var obst = [];
function drawDino() {
var dinoImg = new Image();
dinoImg.src = 'http://lorempixel.com/400/200/'; //'dino.png';
dinoImg.onload = function() {
ctx.drawImage(dinoImg, 0, 0, 100, 100);
}
}
function drawObst() {
}
function draw() {
drawDino();
drawObst();
}
function startGame() {
setInterval(draw,1000);
}
startGame();
}
<canvas id="gameArea"></canvas>
Upvotes: 1
Reputation: 1165
I believe this is what you are looking for.
You did not pass width & height parameters to drawIamge
ctx.drawImage(dinoImg, x, y, width, height);
Read more at:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
window.onload = function() {
var cvs = document.getElementById("gameArea");
var ctx = cvs.getContext("2d");
var dino;
var obst = [];
function drawDino() {
var dinoImg = new Image();
dinoImg.src = 'https://i.imgur.com/HeGEEbu.jpg';
dinoImg.onload = function() {
//ctx.drawImage(dinoImg, 0, 0);
let width = 200;
let height = 200;
ctx.drawImage(dinoImg, 0, 0, width, height);
}
}
function drawObst() {
}
function draw() {
drawDino();
drawObst();
}
function startGame() {
setInterval(draw,50);
}
startGame();
}
#gameArea {
border:1px solid;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<canvas id="gameArea" width="500" height="500"></canvas>
</body>
</html>
Upvotes: 1