3

i'm currently trying to load a base64 img into my canvas

  console.log('Change');
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
    var image = new Image();
    image.onload = function() {
      ctx.drawImage(image, 0, 0);
    };
    image.src = stack[1].save;

stack[1].save contains a valid base64 png img URL('data:image/png;base64,xxxxxx'), when i paste this URL into my browser i can see a valid img

The fact is that nothing changes and i dont have any error

If you could help me this will be awesome, thank's

thomasA
  • 257
  • 1
  • 4
  • 11
  • 'Change' gets logged? What if you add an `image.error=console.error`? And the string you provided `URL(data...` is not a valid dataURI. `URL(`part should not be there. Please try to be as complete and exact as possible. – Kaiido Aug 11 '18 at 23:32
  • Does this answer your question? [Base64 PNG data to HTML5 canvas](https://stackoverflow.com/questions/4409445/base64-png-data-to-html5-canvas) – li x Nov 24 '20 at 13:20

1 Answers1

6

Yes the code you have shared should work OK.

Here is an example

const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')

var image = new Image();
image.onload = () => { ctx.drawImage(image, 0, 0) }
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAQAAAAngNWGAAAAF0lEQVR42mNk+M9AFGAcVTiqcFQhCAAAf0sUAaSRMCEAAAAASUVORK5CYII="

var image2 = new Image()
image2.onload = () => { for(i=1; i<9; i++) ctx.drawImage(image2, 30*i, 5+4*i) }
image2.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg=="
<canvas id="canvas"></canvas>

The only thing that could be wrong is that stack[1].save that you are using...

Helder Sepulveda
  • 15,500
  • 4
  • 29
  • 56
  • To request more informations from asker, please use the comments instead of an answer. – Kaiido Aug 11 '18 at 23:31
  • Thank's your for your reply, it was helpfull i've found my error by testing your code. The fact was that i did'nt clear my canvas before change the img, the img was a backup of that canvas (i'm drawing on the canvas) so we were stil seeing the actual canvas – thomasA Aug 11 '18 at 23:33
  • for me i changed ctx.drawImage(image,canvas.width,canvas.height) anf it was not working ! so check there is ctx.drawImage(image,canvas.0,0), i dont know what mean 0 here – cyril Jul 20 '22 at 06:07
  • @cyril see the documentation for drawImage: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage ... you can use values other than 0 there, I just added a sample there – Helder Sepulveda Jul 20 '22 at 10:15