Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Canvas element to string

In general we can convert the HTML elements to string and then we can insert it into DOM later when needed. Similarly, I want to convert the "CANVAS" element to string along with its context properties.

In the following example, I am getting the string value of span tag with outerHTML property. Likewise I want to get the "CANVAS"element along with context properties.

Is there any method or property for this support?

Example code snippets:

var sp=document.createElement("span");
sp.innerHTML = "E2"
var e2 = sp.outerHTML;
$("#test1").append(e2);

var c=document.createElement("CANVAS");
var ctx=c.getContext("2d");
ctx.beginPath(); 
ctx.moveTo(20,20);           
ctx.lineTo(100,20);          
ctx.arcTo(150,20,150,70,50); 
ctx.lineTo(150,120);         
ctx.stroke(); 
var cn = c.outerHTML;
$("#test2").append(cn);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1">
<span>E1</span>
</div>

<div id="test2">

</div>
like image 623
John R Avatar asked Oct 30 '22 00:10

John R


1 Answers

Seems like you already know how to get dom properties of the canvas object. Now you only need "context" infos (image data as I understand it)

You can get the image data as a base64 string like this:

function CreateDrawing(canvasId) {
  let canvas = document.getElementById(canvasId);
  let ctx = canvas.getContext('2d');
  ctx.beginPath(); 
  ctx.moveTo(20,20);           
  ctx.lineTo(100,20);          
  ctx.arcTo(150,20,150,70,50); 
  ctx.lineTo(150,120);         
  ctx.stroke();
}

function GetDrawingAsString(canvasId) {
  let canvas = document.getElementById(canvasId);
  let pngUrl = canvas.toDataURL(); // PNG is the default
  // or as jpeg for eg
  // var jpegUrl = canvas.toDataURL("image/jpeg");
  return pngUrl;
}

function ReuseCanvasString(canvasId, url) {
  let img = new Image();
  img.onload = () => {
    // Note: here img.naturalHeight & img.naturalWidth will be your original canvas size
    let canvas = document.getElementById(canvasId);
    let ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);
  }
  img.src = url;
}

// Create something
CreateDrawing("mycanvas");
// save the image data somewhere
var url = GetDrawingAsString("mycanvas");
// re use it later
ReuseCanvasString("replicate", url);
<canvas id="mycanvas"></canvas>
<canvas id="replicate"></canvas>
like image 54
Apolo Avatar answered Nov 14 '22 06:11

Apolo