JavaScript encodes Base64 to display images in Canvas

Asked 2 years ago, Updated 2 years ago, 126 views

function addMessage(value,color,size){

    varcanvas= document.getElementById("picture");
    varctx=canvas.getContext("2d");
    var image = new Image();
    variable image.src=""data:image/jpg;base64,"+window.btoa(value)+""";
    image.onload=function(){
      ctx.drawImage(image,0,0);
    }
    varmsg=value.replace(/[!@$%<'>'&|]/g,');
    $("#msg_list").prepend("<div class='msg'>"+msg+"</div>");
  } 

I want to send an image from Android via the server and display it in my browser, but it doesn't work.

On the Android side, I am sending it as string because I want to make the image binary and make it easier for the browser to process it. The string displayed on both Android and browser sides is the same, so there seems to be no problem on the server side.

I only have JavaScript code on it, but if you know anyone, could you please check if the writing is correct?

javascript image html5-canvas

2022-09-30 15:48

2 Answers

Is there an error because it says var image.src?
It hasn't been verified yet, but I think it will work.

function addMessage(value,color,size){

    varcanvas= document.getElementById("picture");
    varctx=canvas.getContext("2d");
    var image = new Image();
    image.onload=function(){
      ctx.drawImage(image,0,0);
    }
    image.src="data:image/jpg;base64,"+window.btoa(value);

    varmsg=value.replace(/[!@$%<'>'&|]/g,');
    $("#msg_list").prepend("<div class='msg'>"+msg+"</div>");
} 

Reference (Pierre's answer):
Convert and insert Base 64 data to Canvas in Javascript


2022-09-30 15:48

I'm not sure if the value is correct, so there may be more, but I'm worried about not needing &quot; and where the lines that register onload are located.

Specifically

var image.src="&quot;data:image/jpg;base64,"+window.btoa(value)+"&quot;";

The row in is

var image.src="data:image/jpg;base64,"+window.btoa(value);

However, the onload line is like moving before the image.src configuration (Related)


2022-09-30 15:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.