E
E
Erik Mikoyan2020-01-05 16:11:20
Canvas
Erik Mikoyan, 2020-01-05 16:11:20

How to embed image on canvas NOT only on load?

I have a canvas and I need to use the same image there multiple times. Can I somehow write it to a variable, and then just pass it to ctx.drawImage? How to do it without img.onload?

const image = new Image();
image.src = src;
image.onload = () => {
texture = image;
};

How can I use texture from above conditional code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dollar, 2020-01-05
@erik_mikoyan

With data:URL (RFC 2397).

Example
<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0j
vb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAA
Re8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0Cc
guWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" width="16" 
height="14">

By the way, the download will still be. You just transfer the image from a separate file to the page itself, increasing its load time. Sometimes it's justified. But if the pictures are large, then you simply deprive yourself of the opportunity to show some kind of preloader so that the user does not get bored while waiting.
Accordingly, your code should be changed like this:
The code
const image = new Image();
image.src = strDataURI; // картинка уже в строке
texture = image;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question