简体   繁体   中英

Functions, and Image importing

I'm working on a project in game development in Javascript and HTML5 canvas. I have this common code I use for loading sprites:

var sprite = new Image();
sprite.src = "sprite.png";

I was wondering if there was a simpler way to do this, which I first thought by function, but not sure how I should do so. I would think to do so like this:

function loadSprite(src) {
this.src = src;
}
var loadSprite(sprite.png);

However I don't think this is the right way to do it. Could someone correct my code and/or give a simpler way of loading an image like this? (I am also using a ctx.drawImage(..., sprite) in order to change coordinates on the canvas so it needs an x,y,width,and height parameters in one way or another)

Why not use as below:

function loadSprite(src) {
var sprite = new Image();
sprite.src = src;
return sprite
}

var _local_var = loadSprite('sprite.png');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM