Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get image from canvas element and use it in img src tag?

Is there possibility to convert the image present in a canvas element into an image representing by img src?

I need that to crop an image after some transformation and save it. There are a view functions that I found on the internet like: FileReader() or ToBlop(), toDataURL(), getImageData(), but I have no idea how to implement and use them properly in JavaScript.

This is my html:

<img src="http://picture.jpg" id="picture" style="display:none"/> <tr>     <td>         <canvas id="transform_image"></canvas>     </td> </tr> <tr>     <td>         <div id="image_for_crop">image from canvas</div>     </td> </tr> 

In JavaScript it should look something like this:

$(document).ready(function() {     img = document.getElementById('picture');     canvas = document.getElementById('transform_image');      if(!canvas || !canvas.getContext){         canvas.parentNode.removeChild(canvas);     } else {         img.style.position = 'absolute';     }     transformImg(90);     ShowImg(imgFile); }  function transformImg(degree) {     if (document.getElementById('transform_image')) {         var Context = canvas.getContext('2d');         var cx = 0, cy = 0;         var picture = $('#picture');         var displayedImg = {             width: picture.width(),             height: picture.height()         };            var cw = displayedImg.width, ch = displayedImg.height         Context.rotate(degree * Math.PI / 180);         Context.drawImage(img, cx, cy, cw, ch);     } }  function showImg(imgFile) {     if (!imgFile.type.match(/image.*/))     return;      var img = document.createElement("img"); // creat img object     img.id = "pic"; //I need set some id     img.src = imgFile; // my picture representing by src     document.getElementById('image_for_crop').appendChild(img); //my image for crop } 

How can I change the canvas element into an img src image in this script? (There may be some bugs in this script.)

like image 366
kassprek Avatar asked Apr 21 '12 09:04

kassprek


People also ask

How do I convert a canvas object to an image?

function convertCanvasToImage() { let canvas = document. getElementById("canvas"); let image = new Image(); image. src = canvas. toDataURL(); return image; } let pnGImage = convertCanvasToImage(); document.

How do I get an image src on canvas?

To get the image data URL of the canvas, we can use the toDataURL() method of the canvas object which converts the canvas drawing into a 64 bit encoded PNG URL. If you'd like for the image data URL to be in the jpeg format, you can pass image/jpeg as the first argument in the toDataURL() method.

What images does IMG tag support?

The <img> tag may support (depending on the browser) the following image formats: jpeg, gif, png, apng, svg, bmp, bmp ico, png ico.


2 Answers

canvas.toDataURL() will provide you a data url which can be used as source:

var image = new Image(); image.id = "pic"; image.src = canvas.toDataURL(); document.getElementById('image_for_crop').appendChild(image); 

Complete example

Here's a complete example with some random lines. The black-bordered image is generated on a <canvas>, whereas the blue-bordered image is a copy in a <img>, filled with the <canvas>'s data url.

// This is just image generation, skip to DATAURL: below var canvas = document.getElementById("canvas") var ctx = canvas.getContext("2d");  // Just some example drawings var gradient = ctx.createLinearGradient(0, 0, 200, 100); gradient.addColorStop("0", "#ff0000"); gradient.addColorStop("0.5" ,"#00a0ff"); gradient.addColorStop("1.0", "#f0bf00");  ctx.beginPath(); ctx.moveTo(0, 0); for (let i = 0; i < 30; ++i) {   ctx.lineTo(Math.random() * 200, Math.random() * 100); } ctx.strokeStyle = gradient; ctx.stroke();  // DATAURL: Actual image generation via data url var target = new Image(); target.src = canvas.toDataURL();  document.getElementById('result').appendChild(target);
canvas { border: 1px solid black; } img    { border: 1px solid blue;  } body   { display: flex; } div + div {margin-left: 1ex; }
<div>   <p>Original:</p>   <canvas id="canvas" width=200 height=100></canvas> </div> <div id="result">   <p>Result via &lt;img&gt;:</p> </div>

See also:

  • MDN: canvas.toDataURL() documentation
like image 148
Zeta Avatar answered Oct 16 '22 12:10

Zeta


Do this. Add this to the bottom of your doc just before you close the body tag.

<script>     function canvasToImg() {       var canvas = document.getElementById("yourCanvasID");       var ctx=canvas.getContext("2d");       //draw a red box       ctx.fillStyle="#FF0000";       ctx.fillRect(10,10,30,30);        var url = canvas.toDataURL();        var newImg = document.createElement("img"); // create img tag       newImg.src = url;       document.body.appendChild(newImg); // add to end of your document     }      canvasToImg(); //execute the function </script> 

Of course somewhere in your doc you need the canvas tag that it will grab.

<canvas id="yourCanvasID" /> 
like image 30
honkskillet Avatar answered Oct 16 '22 14:10

honkskillet