简体   繁体   中英

Image not drawing into the canvas using base64 string data

I tried to draw an image into canvas using base64 data. Transparent canvas appears on the screen without image.

HTML code

<canvas id="c" style ="position: absolute; border: solid; border-color: #000000;"></canvas>

Code behind

byte[] imgBytes = binaryReader.ReadBytes((int) stream.Length);
System.Drawing.Image img = System.Drawing.Image.FromStream(new System.IO.MemoryStream(imgBytes));
String base64String = Convert.ToBase64String(imgBytes);
String src = String.Format("data:image/png;base64,{0}\"", base64String);
ScriptManager.RegisterStartupScript(this, this.GetType(), "Javascript", "javascript:drawMap(" + src + "); ", true);

JavaScript

var htmlCanvas = document.getElementById("c");
var context = htmlCanvas.getContext("2d");

function drawMap(imgdata) {
  var image = new Image();
  image.onload = function() {
    ctx.drawImage(image, 0, 0);
  };
  image.src = imgdata;
}

You have some errors in your JavaScript. Here is a working example:

 var htmlCanvas = document.getElementById("c"); var ctx = htmlCanvas.getContext("2d"); function drawMap(imgdata) { var image = new Image(); image.onload = function() { ctx.drawImage(image, 0, 0); }; image.src = imgdata; } drawMap("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAFUlEQVR42mNk+M9Qz0AEYBxVSF+FAAhKDveksOjmAAAAAElFTkSuQmCC"); 
 <canvas id="c" style="position: absolute; border: solid; border-color: #000000;"></canvas> 

Also you must enclose the image data string in quotes when you're passing it to the drawMap() function and don't proceed it with javascript: :

ScriptManager.RegisterStartupScript(this, this.GetType(),
             "Javascript", "drawMap('" + src + "');", true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM