我正在学习如何使用javascript制作迷你游戏,但是我的播放器未渲染。 我不知道为什么。我没有任何错误。
startGame()以
开头我应该如何编辑代码以使其运行并让精灵进行渲染?
这是我的代码:
<html>
<head>
<meta name="viewport" content="width = device-width, initial-scale = 1.0"/>
</head>
<body onload='startGame()'>
<script>
function startGame() {
createCanvas.start();
}
let ninja = new Image();
let ninjaImage = "images/player/stand01.png"
const createCanvas = {
canvas : document.createElement('canvas'),
start() {
this.canvas.width = 600;
this.canvas.height = 400;
this.context = this.canvas.getContext('2d');
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
}
}
function sprite(options){
let that = {};
that.context = options.context;
that.width = options.width;
that.height = options.height;
that.image = options.image;
return that;
that.render = function () {
that.context.drawImage(
that.image, 0, 0, that.width, that.height, 0, 0, that.width, that.height);
}
player.render();
}
player = sprite ({
width: 100,
height: 100,
image: ninjaImage
});
</script>
</body>
<style>
canvas {
border: 1px solid black;
background: grey;
}
</style>
答案 0 :(得分:0)
假设您已经做好了提早返还的工作,那么您的代码将无法正常工作,因为您可能是因为在创建播放器对象时调用了render()函数。在绘制任何内容之前,最好先设置画布和上下文对象。
我建议以类似方式创建对象的方法是使用函数/原型方法。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
display: block;
margin: auto;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
void function() {
"use strict";
/*
In JS a 'class' is made up of two things
A constructor function that attaches individual properties to every new instance
(When a contructor is called with 'new' I.E. 'new Sprite()', the 'this' variable in the constructor
is assigned to the newly created object.
The other part is a prototype that holds shared properties between instances of
the 'class'. (in an instance prototype values are accessible via the this keyword).
*/
// Constructor function
function Sprite(x,y,width,height,image) {
this.x = x || 0.0;
this.y = y || 0.0;
this.width = width || 1.0;
this.height = height || 1.0;
this.image = image || null;
}
// Prototype object (Shared between instances)
Sprite.prototype = {
render: function(ctx) {
if (this.image) {
ctx.drawImage(this.image,this.x,this.y,this.width,this.height);
} else {
ctx.fillStyle = "darkred";
ctx.fillRect(this.x,this.y,this.width,this.height);
}
}
};
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var sprite = null;
var image = new Image();
image.src = "https://i.stack.imgur.com/WnNgY.png";
// window.onload, called when page has loaded
onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
ctx.fillStyle = "gray";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
sprite = new Sprite(65,55,50,50,image);
sprite.render(ctx);
}
}();
</script>
</body>
</html>