0
\$\begingroup\$

I'm very new to sprites and I'm trying to figure out how to use them. I want to use a simple solution. Something like this:

var c = document.getElementById ('canvas) var ctx = c.getContext ('2d'); ctx.upload('image/testImage');

I'm very sorry if the solution is an obvious one, I'm not very good at JS. I am using pure JavaScript, I don't really like using engines.

\$\endgroup\$
3
  • \$\begingroup\$ You should probably specify an engine or framework that you're using, otherwise there's not much specific help we can give. Also, normally with WebGL (and thus any js engine in the browser), it's really accepting of any image format, .png, .jpg, etc and it'll handle the rest. Also this page on MDN "Using textures in WebGL" should help. \$\endgroup\$ – Coburn Oct 12 '16 at 16:43
  • \$\begingroup\$ Per your editted question, is it a WebGL canvas or a 2D canvas? \$\endgroup\$ – Coburn Oct 13 '16 at 13:57
  • \$\begingroup\$ I'm using a 2D canvas \$\endgroup\$ – The Gamer King Oct 13 '16 at 13:58
1
\$\begingroup\$

It is indeed really easy and you could find it easily by yourself...

image = new Image();
image.src = "path";
ctx.drawImage(image, ...);
\$\endgroup\$
1
\$\begingroup\$

A sprite in most setups is just a normal basic object (position, rotation, etc) that renders as a quad with some sort of texture. In a 2D canvas, if you have your own basic object class, you would want to render your sprite using CanvasRenderingContext2D.drawImage(...). To quote from MDN the parameters are:

void ctx.drawImage(image, dx, dy);
void ctx.drawImage(image, dx, dy, dWidth, dHeight);
void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

image
An element to draw into the context. The specification permits any canvas image source (CanvasImageSource), such as an HTMLImageElement, an HTMLVideoElement, an HTMLCanvasElement or an ImageBitmap.

...

The image parameter has quite a few possible classes that you can use as your image source the most used of those being HTMLImageElement. Here's how it's used.

var img = new Image(); //Creates an HTMLImageElement
img.src = "localhost/myImg.png";
img.addEventListener("load", function() {
    ctx.drawImage(img, 0, 0);
});

Note: When loading external images you must deal with cross origin requests. To get it to work, you'll need to CORS enable your image or it will taint your canvas and you won't be able to render it.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.