我不知道如何更改图像的格式。我正在尝试使用Google Chrome浏览器制作Dino游戏。而且更改图像大小将不起作用。
我的代码:
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();
}
答案 0 :(得分:1)
我相信这就是您想要的。
您没有将width和height参数传递给drawIamge
ctx.drawImage(dinoImg, x, y, width, height);
了解更多信息:
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>
答案 1 :(得分:1)
使用drawImage
的参数调整图像大小。
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>