How to convert canvas image to standard img? [duplicate] - javascript

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.)

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 <img>:</p>
</div>
See also:
MDN: canvas.toDataURL() documentation

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" />

I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.
the method is not toDataUrl(); is toDataURL(); and you forgot to store the canvas in your variable.
So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/
I hope this helps!

canvas.toDataURL is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.

Corrected the Fiddle - updated shows the Image duplicated into the Canvas...
And right click can be saved as a .PNG
http://jsfiddle.net/gfyWK/67/
<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>
Plus the JS on the fiddle page...
Cheers
Si
Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....

Related

HTML Canvas Will Not Draw Image

Okay, I know that there are loads of subjects that look identical to this one on SO, but none of them have fixed my issue...
I'm trying to grab an image from a file input and throw it onto a canvas so that I can later turn it into a base-64 image... But I've hit a snag in the process that I was not expecting, in drawing the image to the canvas...
Taking the following HTML:
<input type="file" id="fileIn" onchange="preview()"><br>
<img id="filePreview"><br>
<canvas id="fileCanvas"></canvas>
And the following script:
var dataurl = '';
function preview(){
document.getElementById('filePreview').src = URL.createObjectURL(document.getElementById('fileIn').files[0]);
document.getElementById('filePreview').onload = showInCanvas;
cnv = document.getElementById('fileCanvas');
ctx = cnv.getContext('2d');
}
function showInCanvas(){
cnv.style.width = document.getElementById('filePreview').naturalWidth + 'px';
cnv.width = document.getElementById('filePreview').naturalWidth;
cnv.style.height = document.getElementById('filePreview').naturalHeight + 'px';
cnv.height = document.getElementById('filePreview').naturalHeight + 'px';
ctx.clearRect(0, 0, cnv.width, cnv.height);
ctx.drawImage(document.getElementById('filePreview'), 0, 0);
dataurl = cnv.toDataURL('image/png');
}
The problem I'm having is that the image simply refuses to draw onto the canvas. Even going into the console and drawing the image to the canvas manually, after the script has run, it still refuses to draw. Because of this, the image data simply runs through as data:,
It's an https site, if that affects anything.
For clarification, here's my question:
Why is the canvas refusing to render this image? How can I fix this issue?
If the intent is to convert the image to Data-URI ("base64"), the FileReader can be used - no need for canvas (which can also alter the image/final compression):
fileIn.onchange = function(e) {
var fr = new FileReader();
fr.onload = done.bind(fr);
fr.readAsDataURL(e.target.files[0]);
}
function done() {
var dataURI = filePreview.src = this.result;
alert(dataURI.substr(0, 35) + "...")
}
<input type="file" id="fileIn"><br>
<img id="filePreview"><br>
<canvas id="fileCanvas"></canvas>

Save Canvas image on Ipad

The webpage is being run on Safari on an iPad.
I have a canvas with the id "canvas1div". I would like to be able to receive this canvas as an image either by email or directly into the photo library.
Via Photo Library
With regards to the photo library, I found this question
Save canvas image on local mobile storage for IOS/Android
This is the function that I would like to call to save the image
function saveimage() {
window.canvas2ImagePlugin.saveImageDataToLibrary(
document.getElementById('canvas1div')
);
}
I don't know how to manually add the plug in to javascript so any advice here would be greatly appreciated.
Email
Again I don't know how to convert the canvas to an image and email it.
Thank you for your help
Don't know if this helps you but here you can find download but email send from JavaScript with email cannot be done:
Example with download file below http://jsfiddle.net/oa2s5eu7/1/
Javscript:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
// Converts image to canvas; returns new canvas element
function convertImageToCanvas(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas;
}
// Converts canvas to an image
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
document.getElementById('mydownload').onclick= function(){
var image = convertCanvasToImage(document.getElementById("myCanvas"));
var anchor = document.createElement('a');
console.log(anchor);
anchor.setAttribute('href', image.src);
anchor.setAttribute('download', 'image.png');
anchor.click();
}
document.getElementById('sendEmail').onclick= function(){
var image = convertCanvasToImage(document.getElementById("myCanvas"));
window.open('mailto:test#example.com?subject=subject&body=you cann send only txt from javscript in email ', '_blank');
}
Html:
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<button id='mydownload'>Download Image</button>
<button id='sendEmail'>Send Email</button>

Javascript - image displaying over text

The code runs with no bugs, but a problem I am having is because the ".onLoad" function makes it display after the text has already been displayed on the screen. The problem I am facing is that I would like if the text (Loading graphics and loading variables) displayed over the image.
The code is here:
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml1-transitional.dtd">
<html>
<body>
<canvas id="ctx" width="800" height="500" style="border:1px solid #d3d3d3;"></canvas>
<script>
var ctx = document.getElementById("ctx").getContext("2d");
var canvas = document.getElementById('ctx');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj,0,0);
};
imageObj.src = 'img/startscreen.jpg';
ctx.fillText('Loading variables.',50,50);
character=new Object();
character.hp=1;
character.name=null;
ctx.fillText('Loading graphics..',50,100);
</script>
</body>
</html>
I would layer the background image on its own canvas positioned behind the text layer. Then you can clear and update the text layer without having to re-draw the background image.
#background,#overlay {
position: absolute;
}
<canvas id="background"></canvas>
<canvas id="overlay"></canvas>
var can = document.getElementById('overlay'),
bg_can = document.getElementById('background'),
height = can.height = bg_can.height = 500,
width = can.width = bg_can.width = 500,
ctx = can.getContext('2d'),
bctx = bg_can.getContext('2d');
var img = new Image();
img.src = ' ... ';
img.onload = init;
function init() {
// draw the background
bctx.drawImage(this, 0, 0);
// draw your initial text
updateText('hello world');
// other stuff that is going to take time
updateText('done');
}
function updateText(msg) {
ctx.clearRect(0, 0, width, height);
ctx.fillText(msg, 50, 100);
}
This isn't very well thought out (my code example) for re-use purposes.. but I don't know much about your other needs :) hope this helps.
If you want to overlay String on image, why don you use image as backGround imange and place text over it??
Css
try in css
#ctx{
background-image:url('img/startscreen.jpg');}
remove image source in script or insert css in script itself
Css in scripts
ctx.style.backgroundImage=url('img/startscreen.jpg');
I called the function for the text to be displayed after the background has:
imageObj.src = 'img/startscreen.jpg';
imageObj.onload = function(){
context.drawImage(imageObj,0,0);
init()
};
function init(){
ctx.fillText('Loading variables.',50,50);
character=new Object();
character.hp=1;
character.name=null;
ctx.fillText('Loading graphics..',50,100);
}

Cannot save canvas with draggable object

I'm trying to save my HTML canvas to file which I can successfully do, but it's not saving any objects I've dragged into the canvas.
So, by using the Draggable JQuery I can happily move my object around screen and place it ontop of my canvas. When I save the canvas using the Canvas.ToDataURL() it does not save my dragged objects (and also does something strange to my canvas in the jsFiddle, it appears to change the colour of my canvas?).
To see a "working" example, please visit my jsFiddle http://jsfiddle.net/JVSFS/74/
Please simply drag the green box over the blue box and click the save button. The result will be shown underneath (just an orange box).
HTML
<canvas id="MyCanvas" class="canvas"></canvas>
<div class="popup_click">
<div id="popup_title">Drag</div>
</div>
<asp:HiddenField ID="hideMe" runat="server" />
<asp:Button runat="server" OnClick="ClickMe" Text="Click" OnClientClick="SaveMe()" />
<button onclick="SaveMe()">Try it</button>
<p>Results: </p>
<img id="myImage" />
JavaScript
$(document).ready(function () {
$('.popup_click').show(0).draggable();
});
function SaveMe() {
var canvas = document.getElementById("MyCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "orange";
context.fillRect(0, 0, 100, 100);
var image = canvas.toDataURL("image/png");
document.getElementById("myImage").src = image;
document.getElementById("hideMe").value = image;
}
CSS
.popup_click {
background: #80FF80;
width: 50px; }
.canvas {
width: 100px;
height: 100px;
background-color: #0FC;
}
How can I get the dragged object to save? I assume I have to tell the Canvas that the object is part of it's context but no idea how and my own searches came up with nothing.
From https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas
You can't just draw HTML into a canvas. Instead, you need to use an SVG image containing the content you want to render. To draw HTML content, you'd use a element containing the HTML, then draw that SVG image into your canvas.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var data = "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
"<foreignObject width='100%' height='100%'>" +
"<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>" +
"<em>I</em> like <span style='color:white; text-shadow:0 0 2px blue;'>cheese</span>" +
"</div>" +
"</foreignObject>" +
"</svg>";
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
};
img.src = url;
That's because your draggable object isn't in the canves.
They are simple html elements.
It'll save only the objects whose created with canvas methods.
Any way to create html elements on canvas you have to use svg.
Mozilla show nice way to to this but you need to get all the css to inline css before.
mozilla explanation
Anyway with using svg on you canvas you won't be able to use toDataUrl because of security policy.

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.)
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 <img>:</p>
</div>
See also:
MDN: canvas.toDataURL() documentation
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" />
I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.
the method is not toDataUrl(); is toDataURL(); and you forgot to store the canvas in your variable.
So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/
I hope this helps!
canvas.toDataURL is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.
Corrected the Fiddle - updated shows the Image duplicated into the Canvas...
And right click can be saved as a .PNG
http://jsfiddle.net/gfyWK/67/
<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>
Plus the JS on the fiddle page...
Cheers
Si
Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....

Categories

Resources