# How add a sprite to canvas using JavaScript?

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.

• 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. – Coburn Oct 12 '16 at 16:43
• Per your editted question, is it a WebGL canvas or a 2D canvas? – Coburn Oct 13 '16 at 13:57
• I'm using a 2D canvas – The Gamer King Oct 13 '16 at 13:58

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

image = new Image();
image.src = "path";
ctx.drawImage(image, ...);


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";