How to download the screenshot automatically by using html2Canvas - javascript

I have a canvas which shows a graph and I'm trying to take a screenshot of the canvas using html2canvas() with the code below :
<div class="chartContainer" id="chart1"></div>
<div id="displayCanvas" style="display:none;" class="stx-dialog"></div>
html2canvas($('#chart1'),{onrendered:function(canvas1)
{$('#displayCanvas').append(canvas1)}});
Here when the chart container is loaded the it uses the div with the id "displayCanvas" and appends the screenshot of the canvas.
How can I download the screenshot of the canvas which is displayed?
I have already tried using something like below to download the image:
var link = document.createElement('a');
link.download = stx.chart.symbol+".png";
link.href = stx.chart.canvas.toDataURL("png");
link.click();
but it only downloads the data on the canvas as an image without the background (it does not download the screenshot but only the data) which when opened after downloading shows a black screen with data in it. Can anyone help me on how to download the image directly of the screenshot taken from the html2Canvas()?

TRY THIS:
In the HTML:
Give the element that you want to screenshot, an ID of "capture".
Give the button/element that you would need to click to take the screenshot, an ID of "btn".
Load the html2canvas.min.js file.
In the Javascript:
Create the capture() function.
Bind the capture() function to whatever event you are using—in this case it's on the btn click event.
DONE! Watch the magic happen when you click on the btn.
HTML:
<h1 id="capture">Hellooooo</h1>
<button id="btn">Capture</button>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
Javascript:
function capture() {
const captureElement = document.querySelector('#capture') // Select the element you want to capture. Select the <body> element to capture full page.
html2canvas(captureElement)
.then(canvas => {
canvas.style.display = 'none'
document.body.appendChild(canvas)
return canvas
})
.then(canvas => {
const image = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream')
const a = document.createElement('a')
a.setAttribute('download', 'my-image.png')
a.setAttribute('href', image)
a.click()
canvas.remove()
})
}
const btn = document.querySelector('#btn')
btn.addEventListener('click', capture)
Here's the JSFiddle
💡 QUICK TIP: If you want to capture the whole document/webpage, then just add the "capture" ID to the <body> tag.

If there is black background at image your chart must be visible on screen. Because html2canvas like a taking screenshot. If you want converting data
to canvas, you must be sure data is appear in screen.

In case someone is using React, here is some code you can copy:
async function download() {
const canvas = await html2canvas(document.querySelector("#screenshot"));
canvas.style.display = "none";
document.body.appendChild(canvas);
const image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
const a = document.createElement("a");
a.setAttribute("download", `info.png`);
a.setAttribute("href", image);
a.click();
}
<a href="#" onClick={() => download()}>Download</a>

This worked for me:
HTML
<div id="canvasDiv">
<canvas id="canvas" height="100" width="100">
Your browser does not support the HTML canvas tag.
</canvas>
</div>
<button onclick="screenShot()" type="button">Take a screenshot</button>
Javascript
function screenShot(){
html2canvas(document.querySelector("#canvasDiv")).then(canvas => {
var dataURL = canvas.toDataURL( "image/png" );
var data = atob( dataURL.substring( "data:image/png;base64,".length ) ),
asArray = new Uint8Array(data.length);
for( var i = 0, len = data.length; i < len; ++i ) {
asArray[i] = data.charCodeAt(i);
}
var blob = new Blob( [ asArray.buffer ], {type: "image/png"} );
saveAs(blob, "photo.png");
});
}
I just used the code provided in html2canvas site, then i used this code to download the screenshot.

Related

Copy QR CODE image to clipboard and paste to share. I use Vuejs? [duplicate]

Seemingly, you can't (yet) programmatically copy an image to the clipboard from a JavaScript web app?
I have tried to copy a text in clipboard , and it's worked.
Now I would like to copy an image and after I press ctrl+v to paste into Word or Excel or Paint.
$(function() {
$("#btnSave").click(function() {
html2canvas($("#container1"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
Canvas2Image.saveAsPNG(canvas);
$("#img-out").append(canvas);
}
});
});
});
For those still looking, the ClipboardAPI now works with png images.
try {
navigator.clipboard.write([
new ClipboardItem({
'image/png': pngImageBlob
})
]);
} catch (error) {
console.error(error);
}
This worked across all browsers (as of 2016). I have uploaded on GitHub as well: https://github.com/owaisafaq/copier-js
//Cross-browser function to select content
function SelectText(element) {
var doc = document;
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
}
$(".copyable").click(function(e) {
//Make the container Div contenteditable
$(this).attr("contenteditable", true);
//Select the image
SelectText($(this).get(0));
//Execute copy Command
//Note: This will ONLY work directly inside a click listenner
document.execCommand('copy');
//Unselect the content
window.getSelection().removeAllRanges();
//Make the container Div uneditable again
$(this).removeAttr("contenteditable");
//Success!!
alert("image copied!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="copyable">
<img src="https://via.placeholder.com/80" alt="Copy Image to Clipboard via Javascript." />
</div>
<div class="copyable">
<img src="https://via.placeholder.com/80" alt="Copy Image to Clipboard via Javascript." />
</div>
So, i created the perfect solution with 1 liner-kinda solution to convert something with html2canvas to a canvas and then produce the image of it and then save it to clipboard as png. For example,
HTML:
<div id="copyToImage">Hello World!</div>
JavaScript:
$("#copyToImage").click(function() {
html2canvas(document.querySelector("#copyToImage")).then(canvas => canvas.toBlob(blob => navigator.clipboard.write([new ClipboardItem({'image/png': blob})])));
});
You are right. There is no support to copy image data into clipboard in chrome yet. https://bugs.chromium.org/p/chromium/issues/detail?id=150835.
Looks like it has been open for about 4 years now.
There is a clipboard API spec that is coming up though
https://w3c.github.io/clipboard-apis/
Well, this is my first post in here with an answer i guess :)
Actually i'm currently using cefsharp web browser component one of my project, cefsharp run on chrome based browser and i want to copy img element one of webpage
With cefsharp you can manipulate browser only javascript, so i think we can handle it with using canvas element.
/*
'cause of lorempixel timeout, i used img onload function.
*/
function copyImage() {
var imgCap = document.getElementById('imgCap');
var imgCanvas = document.createElement('canvas');
imgCanvas.id = 'imgCanvas';
imgCanvas.height = 40;
imgCanvas.width = 120;
document.body.appendChild(imgCanvas);
var originalContext = imgCanvas.getContext('2d');
originalContext.drawImage(imgCap, 0, 0);
//return imgCanvas.toDataURL();
}
//document.onload = copyImage();
<img id="imgCap" src="http://lorempixel.com/120/40" onload="copyImage();"/>
with return imgCanvas.toDataURL(); you can get base64 encoded value and use wherever you want.
this is my cefsharp code, it's working.
string copyImageOtClipboardScript = "(function(){ try{var imgCap = document.getElementById('imgCap'); var imgCanvas = document.createElement('canvas'); imgCanvas.id = 'imgCanvas'; imgCanvas.height = 40; imgCanvas.width = 120; document.body.appendChild(imgCanvas); var originalContext = imgCanvas.getContext('2d'); originalContext.drawImage(imgCap, 0, 0); return imgCanvas.toDataURL(); }catch(e){ alert(e); } })();";
var task = chromeBrowser.EvaluateScriptAsync(copyImageOtClipboardScript).ContinueWith(x =>
{
var resp = x.Result;
if (resp.Success)
{
this.Invoke((MethodInvoker)delegate
{
Bitmap bmp = null;
string captchaResult = "", captchaBase64;
var bytes = Convert.FromBase64String(resp.Result.ToString().Replace("data:image/png;base64,", ""));
using (var imageFile = new FileStream("temp_captcha.png", FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
});
}
});
This can be achieved by using the Clipboard API, which does require that your server is secured. The basic idea is to convert your image to a blob before writing it to the clipboard as an image.
const img = document.querySelector("#b64-img");
const copyBtn = document.querySelector("#copy");
copyBtn.onclick = e => {
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height);
canvas.toBlob((blob) => {
navigator.clipboard.write([
new ClipboardItem({ "image/png": blob })
]);
}, "image/png");
};
<img id="b64-img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQoAAAFmCAMAAACiIyTaAAABv1BMVEUAAAB5S0dJSkpISkpLTU3pSzzoTD3oSzzoTD3kSjvoTD1GRUbeSDpFREVCQULpSzzoTD3c3d3gSTrg4uDm5uZFRETbRznoTD3oTD1JR0iXlYXaRzncRzhBQUDnSjtNS0zUzsdnZmVLSEpMSEoyNjPm5eSZmYfm6ekzNTOloI42ODbm6Oiioo/h4eEzODbm5+eop5SiopCiopDl396hloaDg3ToTD3m5uZMS03///9RTlAAAADy8vIgICA2NzY4OzYPM0fa29qgoI7/zMnj4+PW19VGRkbqPi7v7/D6+vr09fXyTj4rKSvhSTo/Pj/oSDnlMyLsNCI0MTP0///tTT7ZRjizO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5fnnUUGhlRaN7VrstO/jIArgJhTLlgnO6bgYnCRUGAriK6uh8vIgjQVaBSDb/lNjomlNA/p1AVlri1/cr4FYV3Q6Eq7KlU3pGDv6ECNh8qPlQkKeHLVdBjEHT4xf9W9PgxZRdBxmn5x3Ssl3mpxU7wWw4Cilvu+D47vXnIjpafQqcPccf41PXTKdnFw8+gjKBR9rOwW+V9P4uOhyBR6fqZdK3z8T8sDJf52bSQDdplnk0oeH4efWSD85vngEG+CWE5KAk/DyD7Rb6JPqrXB4OeZjQaDYfDe8NQMxr1NINB/Xri59BBEPByTcjqbmrDbodzXby/IfzMlAs11SasXTDgKrwcEyLQJqxdbCYCdkBQJ1MEN+mwchHKdBlMANk2K+nvXtBgZ0zYyZiGXCRtCAWmZFVOq6LSnwcbEecsjF2wkUIIxQ5KJ4KPERyclrGg8XHDiDjbxjTYYKlEBOPNzwMECtfptjo+8yVdNYLqzoi4zMY0CMJ1ozH+3KsjqJTqg95w3G5Xq5erqLbb4/tRb3CD/g9u9h1zNLq/115iqqm0Y8a6fo508azf/FMFPwB+4ZiyTYnf/gAAAABJRU5ErkJggg==">
<br>
<button id="copy">Copy Above Image</button>
This will allow you to paste your image to Photoshop and other image-applications.
Check out this guide to copying and pasting with JavaScript: https://www.lucidchart.com/techblog/2014/12/02/definitive-guide-copying-pasting-javascript/
According to this, Chrome, Safari, and Firefox all support copying images along with plain text, while IE only allows copying text. The page linked above describes how this service uses an extension to add this functionality to a context menu, but it appears that several browsers support programmatic copying of images.
const copyImageToClipboard = async () => {
try {
await navigator.clipboard.write([
new ClipboardItem({
'image/png': await fetch(img).then((r) => r.blob()),
}),
]);
} catch (error) {
console.error(error);
}
};
You might run into CORS errors testing on localhost. But you can install a CORS extension to get rid of that issue :)
var image = new Image();
image.src = url;
copyImageToClipboard(image.src);
install it from https://www.npmjs.com/package/copy-image-clipboard
Here is the best answer i found for you, very simple and its working 100% exactly what you need.
await navigator.clipboard.writeText(code);
Check out this link: enter link description here
You cannot copy to clip board with Javascript for security reasons, a work around can be found in a discussion here. Involves flash.Click button copy to clipboard using jQuery

How to save canvas on Right-Click dialog as jpg

I'm using this code to capture images as canvas from a video URL in my site:
var videoId = 'video';
var scaleFactor = 0.55; // increase or decrease size
var snapshots = [];
/**
* Captures a image frame from the provided video element.
*
* #param {Video} video HTML5 video element from where the image frame will be captured.
* #param {Number} scaleFactor Factor to scale the canvas element that will be return. This is an optional parameter.
*
* #return {Canvas}
*/
function capture(video, scaleFactor) {
if(scaleFactor == null){
scaleFactor = 1;
}
var w = video.videoWidth * scaleFactor;
var h = video.videoHeight * scaleFactor;
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, w, h);
var uniq = 'img_' + (new Date()).getTime();
canvas.setAttribute('id', uniq);
return canvas ;
}
/**
* Invokes the <code>capture</code> function and attaches the canvas element to the DOM.
*/
function shoot(){
var video = document.getElementById(videoId);
var output = document.getElementById('output');
var canvas = capture(video, scaleFactor);
snapshots.unshift(canvas);
output.innerHTML = '' ;
for(var i=0; i<10; i++){
output.appendChild(snapshots[i]);
}
}
My two problems:
1 - Currently, browsers treat <canvas> like they they treat a <div> and this make it impossible to save any generated canvas as an image because when I right-click on each and everyone, it always opens the windows dialog here I have to choose Save image as....
2 - The windows right-click dialog always opens by default the option to save image as transfer.png and I would like to save the image with their ID attribute (var uniq) and a jpg extension.
Example of what I need:
The output canvas is like this: <canvas width="352" height="198" id="img_1575807516362"></canvas>.
I want the right-click to open the windows dialog offering to save image like this img_1575807516362.jpg.
Alternatively, it would be nice tho have a download button for each canvas to export the canvas as an image like this transfer.jpg.
Is it possible to make this work with this code?
Apologies in advance. It took me some time, but I wanted to make sure that I got it working properly. I am not sure if there is a way to do a windows dialog to save to file (Where it pulls up the save as... prompt), but you can definitely create a download button to do this.
Downloading the Image
First, we need to create a download button:
<button onmousedown="download()">Download</button>
Second, we can create a function to download the image with a key.
The easiest way to do this is creating a downloadable <a> tag:
var download = function(){
var link = document.createElement('a'); //Creates an 'a' element
var thisCanvas = document.getElementsByTagName('canvas')[0]; //gets the first canvas element on the page, assuming the canvas you want to download is this element.
link.download = `${thisCanvas.id}.jpeg`; //Gives the download an output link
link.href = thisCanvas.toDataURL("image/jpeg") //Gives the data to the link
link.click(); //Clicks the 'a' element we created
}
If you wanted to ask for user input whether or not they want to download, you can use:
var download = function() {
if (window.confirm("Would you like to download this frame?")) {
var link = document.createElement('a'); //Creates an 'a' element
var thisCanvas = document.getElementsByTagName('canvas')[0]; //Gets the canvas
link.download = `${thisCanvas.id}.jpeg`; //Gives the download an output link
link.href = thisCanvas.toDataURL("image/jpeg") //Gives the data to the link
link.click(); //Clicks the 'a' element we created
}
}
You can always change the name of the image file as well with link.download = imageName + ".jpeg"
Creating A Button in JS
EDIT: If you want to create the button in javascript instead of html, you can do the following:
var createbutton = function() {
var b = document.createElement('button'); //Creates the button
b.onmousedown = function() { //Creates an onmousedown event for the button
download(); //This is the download function above
}
b.innerHTML = "Download"; //Gives the button Text
//Here, you can insert button styles using: b.style
document.body.appendChild(b); //Appends the button to the body
}
You can call this function whenever you need to create the download button. This function creates a button at the end of the body, but you can change the location:
//Where it says document.body.appendChild(b); , replace it with:
document.getElementById(`myCustomId`).appendChild(b);
//This places the button in any element on the page with 'myCustomId'
Canvas onmousedown events, and downloading all images
EDIT (2):
If you have multiple canvases that are created within snapshots, then you can do the following to download all the snapshots:
var download = function(){
var link = document.createElement('a'); //Creates an 'a' element
snapshots.forEach(snap => {
link.download = `${snap.id}.jpeg`; //Gives the download an output link
link.href = snap.toDataURL("image/jpeg") //Gives the data to the link
link.click(); //Clicks the 'a' element we created
});
}
If you want to download one image at a time, you can give them an onmousedown event when you add them. Let's edit the download function to support this:
var download = function(canvas){
var link = document.createElement('a'); //Creates an 'a' element
link.download = `${canvas.id}.jpeg`; //Gives the download an output link
link.href = canvas.toDataURL("image/jpeg") //Gives the data to the link
link.click(); //Clicks the 'a' element we created
}
//We also need to edit the shoot() function
function shoot(){
var video = document.getElementById(videoId);
var output = document.getElementById('output');
var canvas = capture(video, scaleFactor);
canvas.onmousedown = function() {
download(canvas);
}
snapshots.unshift(canvas);
output.innerHTML = '' ;
for(var i=0; i<10; i++){
output.appendChild(snapshots[i]);
}
}
This way whenever you append all of the snapshots, each canvas comes with it's own mousedown event, so clicking on it will return the image. You can even add a confirm box or check if right mouse is clicked here.
Question 2: It doesn't matter where the functions go, only where you call them.
If you have any questions, let me know!

How to change the image a source is associated with

Is there anyway that I can put an image on my site that changes.
I know how to change the source of an image element. What I mean is like:
the image is located here
http://mywebsite.com/image.png
this doesn't change but I want the actual image to change.
More examples:
https://huggle.jdf2.org/
This site creates a bbcode element that contains the img username.png
[url=http://huggle.jdf2.org/hug/username][img]http://huggle.jdf2.org/sig/username.png[/img][/url]
This image changes depending on how many huggles you have.
How would I do this?
You can dynamically set the image source URL with:
var yourURLHere = 'ADD YOUR URL HERE';
image.src = yourURLHere;
If you want the your image to randomly change, you can use Math.random() to select a random URL from an array.
Example: Random teddy bear images (see below).
<image src="#" id="my-image"/>
Click to change image randomly.
<button id="my-btn">Change it!</button>
<script>
var imageURLs = [
'https://s-media-cache-ak0.pinimg.com/originals/4e/da/9f/4eda9f56de08463bcc18d154f654ab6d.jpg',
'http://lcdn.inthelighturns.com/media/product/e85/sweet-memories-blue-teddy-bear-urn-b83.jpg',
'https://s-media-cache-ak0.pinimg.com/originals/3c/80/3c/3c803ce72e8c0325d7ea0fcd32f81ed9.jpg',
'http://cliparting.com/wp-content/uploads/2016/07/Cartoon-teddy-bear-clipart.gif',
'http://cliparts.co/cliparts/rcn/Kox/rcnKox65i.png',
'https://s-media-cache-ak0.pinimg.com/originals/f2/d6/25/f2d6258ef0fa6de2160778066ccec832.jpg',
'https://s-media-cache-ak0.pinimg.com/236x/90/3a/6c/903a6c59c0a2f42e7d6e7cb9427a8337.jpg',
'https://s-media-cache-ak0.pinimg.com/564x/a9/ee/30/a9ee30a4f8d196a111aa5c3db7b13b6e.jpg',
'http://cdn3.volusion.com/9nxdj.fchy5/v/vspfiles/photos/BB-1433-2.jpg?1415360799'
];
var image = document.getElementById('my-image');
function pickRandomURL() {
return imageURLs[Math.floor(Math.random() * imageURLs.length)];
}
image.src = pickRandomURL();
image.width = 200;
var btn = document.getElementById('my-btn');
btn.onclick = function() {
image.src = pickRandomURL();
image.width = 200;
};
</script>

Copy image to clipboard

Seemingly, you can't (yet) programmatically copy an image to the clipboard from a JavaScript web app?
I have tried to copy a text in clipboard , and it's worked.
Now I would like to copy an image and after I press ctrl+v to paste into Word or Excel or Paint.
$(function() {
$("#btnSave").click(function() {
html2canvas($("#container1"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
Canvas2Image.saveAsPNG(canvas);
$("#img-out").append(canvas);
}
});
});
});
For those still looking, the ClipboardAPI now works with png images.
try {
navigator.clipboard.write([
new ClipboardItem({
'image/png': pngImageBlob
})
]);
} catch (error) {
console.error(error);
}
This worked across all browsers (as of 2016). I have uploaded on GitHub as well: https://github.com/owaisafaq/copier-js
//Cross-browser function to select content
function SelectText(element) {
var doc = document;
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
}
$(".copyable").click(function(e) {
//Make the container Div contenteditable
$(this).attr("contenteditable", true);
//Select the image
SelectText($(this).get(0));
//Execute copy Command
//Note: This will ONLY work directly inside a click listenner
document.execCommand('copy');
//Unselect the content
window.getSelection().removeAllRanges();
//Make the container Div uneditable again
$(this).removeAttr("contenteditable");
//Success!!
alert("image copied!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="copyable">
<img src="https://via.placeholder.com/80" alt="Copy Image to Clipboard via Javascript." />
</div>
<div class="copyable">
<img src="https://via.placeholder.com/80" alt="Copy Image to Clipboard via Javascript." />
</div>
So, i created the perfect solution with 1 liner-kinda solution to convert something with html2canvas to a canvas and then produce the image of it and then save it to clipboard as png. For example,
HTML:
<div id="copyToImage">Hello World!</div>
JavaScript:
$("#copyToImage").click(function() {
html2canvas(document.querySelector("#copyToImage")).then(canvas => canvas.toBlob(blob => navigator.clipboard.write([new ClipboardItem({'image/png': blob})])));
});
You are right. There is no support to copy image data into clipboard in chrome yet. https://bugs.chromium.org/p/chromium/issues/detail?id=150835.
Looks like it has been open for about 4 years now.
There is a clipboard API spec that is coming up though
https://w3c.github.io/clipboard-apis/
Well, this is my first post in here with an answer i guess :)
Actually i'm currently using cefsharp web browser component one of my project, cefsharp run on chrome based browser and i want to copy img element one of webpage
With cefsharp you can manipulate browser only javascript, so i think we can handle it with using canvas element.
/*
'cause of lorempixel timeout, i used img onload function.
*/
function copyImage() {
var imgCap = document.getElementById('imgCap');
var imgCanvas = document.createElement('canvas');
imgCanvas.id = 'imgCanvas';
imgCanvas.height = 40;
imgCanvas.width = 120;
document.body.appendChild(imgCanvas);
var originalContext = imgCanvas.getContext('2d');
originalContext.drawImage(imgCap, 0, 0);
//return imgCanvas.toDataURL();
}
//document.onload = copyImage();
<img id="imgCap" src="http://lorempixel.com/120/40" onload="copyImage();"/>
with return imgCanvas.toDataURL(); you can get base64 encoded value and use wherever you want.
this is my cefsharp code, it's working.
string copyImageOtClipboardScript = "(function(){ try{var imgCap = document.getElementById('imgCap'); var imgCanvas = document.createElement('canvas'); imgCanvas.id = 'imgCanvas'; imgCanvas.height = 40; imgCanvas.width = 120; document.body.appendChild(imgCanvas); var originalContext = imgCanvas.getContext('2d'); originalContext.drawImage(imgCap, 0, 0); return imgCanvas.toDataURL(); }catch(e){ alert(e); } })();";
var task = chromeBrowser.EvaluateScriptAsync(copyImageOtClipboardScript).ContinueWith(x =>
{
var resp = x.Result;
if (resp.Success)
{
this.Invoke((MethodInvoker)delegate
{
Bitmap bmp = null;
string captchaResult = "", captchaBase64;
var bytes = Convert.FromBase64String(resp.Result.ToString().Replace("data:image/png;base64,", ""));
using (var imageFile = new FileStream("temp_captcha.png", FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
});
}
});
This can be achieved by using the Clipboard API, which does require that your server is secured. The basic idea is to convert your image to a blob before writing it to the clipboard as an image.
const img = document.querySelector("#b64-img");
const copyBtn = document.querySelector("#copy");
copyBtn.onclick = e => {
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height);
canvas.toBlob((blob) => {
navigator.clipboard.write([
new ClipboardItem({ "image/png": blob })
]);
}, "image/png");
};
<img id="b64-img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQoAAAFmCAMAAACiIyTaAAABv1BMVEUAAAB5S0dJSkpISkpLTU3pSzzoTD3oSzzoTD3kSjvoTD1GRUbeSDpFREVCQULpSzzoTD3c3d3gSTrg4uDm5uZFRETbRznoTD3oTD1JR0iXlYXaRzncRzhBQUDnSjtNS0zUzsdnZmVLSEpMSEoyNjPm5eSZmYfm6ekzNTOloI42ODbm6Oiioo/h4eEzODbm5+eop5SiopCiopDl396hloaDg3ToTD3m5uZMS03///9RTlAAAADy8vIgICA2NzY4OzYPM0fa29qgoI7/zMnj4+PW19VGRkbqPi7v7/D6+vr09fXyTj4rKSvhSTo/Pj/oSDnlMyLsNCI0MTP0///tTT7ZRjizOi+6PDDmLRyenZ7oKRfExMT/TzvobGEVFBWGhYUAGjLW8/ToXVADLUZ8e33/2tfRRTdWVFTFQDT1u7aSkZIADib+5eFwcHHW+/z70tDwkIesPTPW6+teXV2xsbG7u7vY4+Lre3DMzM2qp6jilIxsPT7lg3kdO07m/f4AJjuwsJzftK/fpZ7woJjoVUZBWGj1zMdTaXfcvrrzq6Tby8f+8u8wSlYZNDaQRUKfr7d9j5lpf4vx5ePMsLF/o64s+PNlAAAANnRSTlMAC1IoljoZWm2yloPRGWiJfdjEEk037Esq7Pn24EKjpiX+z7rJN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jqbmrDbodzXby/IfzMlAs11SasXTDgKrwcEyLQJqxdbCYCdkBQJ1MEN+mwchHKdBlMANk2K+nvXtBgZ0zYyZiGXCRtCAWmZFVOq6LSnwcbEecsjF2wkUIIxQ5KJ4KPERyclrGg8XHDiDjbxjTYYKlEBOPNzwMECtfptjo+8yVdNYLqzoi4zMY0CMJ1ozH+3KsjqJTqg95w3G5Xq5erqLbb4/tRb3CD/g9u9h1zNLq/115iqqm0Y8a6fo508azf/FMFPwB+4ZiyTYnf/gAAAABJRU5ErkJggg==">
<br>
<button id="copy">Copy Above Image</button>
This will allow you to paste your image to Photoshop and other image-applications.
Check out this guide to copying and pasting with JavaScript: https://www.lucidchart.com/techblog/2014/12/02/definitive-guide-copying-pasting-javascript/
According to this, Chrome, Safari, and Firefox all support copying images along with plain text, while IE only allows copying text. The page linked above describes how this service uses an extension to add this functionality to a context menu, but it appears that several browsers support programmatic copying of images.
const copyImageToClipboard = async () => {
try {
await navigator.clipboard.write([
new ClipboardItem({
'image/png': await fetch(img).then((r) => r.blob()),
}),
]);
} catch (error) {
console.error(error);
}
};
You might run into CORS errors testing on localhost. But you can install a CORS extension to get rid of that issue :)
var image = new Image();
image.src = url;
copyImageToClipboard(image.src);
install it from https://www.npmjs.com/package/copy-image-clipboard
Here is the best answer i found for you, very simple and its working 100% exactly what you need.
await navigator.clipboard.writeText(code);
Check out this link: enter link description here
You cannot copy to clip board with Javascript for security reasons, a work around can be found in a discussion here. Involves flash.Click button copy to clipboard using jQuery

how to save canvas as png image?

I have a canvas element with a drawing in it, and I want to create a button that when clicked on, it will save the image as a png file. So it should open up the save, open, close dialog box...
I do it using this code
var canvas = document.getElementById("myCanvas");
window.open(canvas.toDataURL("image/png"));
But when I test it out in IE9, a new window opens up saying "the web page cannot be displayed"
and the url of it is:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmAAAABpCAYAAACd+58xAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAADRwSURBVHhe7V0Hg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S0e+LB4vw9sVhiwmHywmF6xqLLdYIQgIAoKAICAICAJVAQHTo2XmkNtzv6K5R7RXLOwRs3MaW+47SNkG9oRxZQmun6qbImCo84VSE+5pR3/zvFZJni/7e8tTHiCeqCkAqsKKig2CgCAgCAgCgoAgUG0RCBKzMLmwkzHdL4pk4XlUAn7Uu3XrVtPqVfO4lurPSq0KQa5cdAv9snBgqM5XFPlKSsSPM8o3mcxES2hZtf0rEMMFAUFAEKiBCEgIsqotavpk/OiwZViHPQk/LgHfHo5EnbCGjVpxeYo9yNmw9oeSn2YeTatWTPNzozzX8ZOeWPJlJVRJnrOoxUtJtmLEUmqoartH7BEEBAFBQBCoJggIASu/hUqkUokC2rZkwSSCBU12wpadhNXbpAk13vwwKlJ3O/L1QmYrxPNlDxuGyVtyIn6K8KSZHwY3XsRX+W0L0VyTEPjwM6KuFxN1uiB6Vkv48MpdjxLt9ieieQvscuvWE13eh2jnQ9zv+F2aICAICAKCQGEIRH22559H5IqnDTMGeU/SgUJ7WNLjOVH9g8/Xrv2Fa4P9SM6K7y4t+WXRw76sfVc42fPV936iJ5+LKrbqTU0P3rA+0dZbEh20L9HJHYj23I2oVrHFT5U5NFnY4m6svUA0Pvo8efbvjCBqtr0nN+IVot4Dkvv1v5aoy/HJcpUpsfI3olffdknV0uWuJfv9kWjkw55VIFAfM073PE4EkqZbEBf9HMTs8C6e3KhHiPbdqzJnKWMLAoJAeSMgHrDyRrj0+rOEGvVoYY9Y0inIeE+YqQ+cqGGj3dgDtvJjC/mKm7BHmG68lGjO+0T
Anyone know how to fix this?
try this:
var canvas = document.getElementById("alpha");
var dataURL = canvas.toDataURL("image/png");
var newTab = window.open('about:blank','image from canvas');
newTab.document.write("<img src='" + dataURL + "' alt='from canvas'/>");
This shows image from canvas on new page, but if you have open popup in new tab setting it shows about:blank in address bar.
EDIT:- though window.open("<img src='"+ canvas.toDataURL('image/png') +"'/>") does not work in FF or Chrome, following works though rendering is somewhat different from what is shown on canvas, I think transparency is the issue:
window.open(canvas.toDataURL('image/png'));
FileSaver.js should be able to help you here.
var canvas = document.getElementById("my-canvas");
// draw to canvas...
canvas.toBlob(function(blob) {
saveAs(blob, "pretty image.png");
});
To accomodate all three points:
button
save the image as a png file
open up the save, open, close dialog box
The file dialog is a setting in the browser.
For the button/save part assign the following function, boiled down from other answers, to your buttons onclick:
function DownloadCanvasAsImage(){
let downloadLink = document.createElement('a');
downloadLink.setAttribute('download', 'CanvasAsImage.png');
let canvas = document.getElementById('myCanvas');
let dataURL = canvas.toDataURL('image/png');
let url = dataURL.replace(/^data:image\/png/,'data:application/octet-stream');
downloadLink.setAttribute('href', url);
downloadLink.click();
}
Example on Codepen
Another, somewhat cleaner, approach is using Canvas.toBlob():
function DownloadCanvasAsImage(){
let downloadLink = document.createElement('a');
downloadLink.setAttribute('download', 'CanvasAsImage.png');
let canvas = document.getElementById('myCanvas');
canvas.toBlob(function(blob) {
let url = URL.createObjectURL(blob);
downloadLink.setAttribute('href', url);
downloadLink.click();
});
}
Example on Codepen
Neither solution is 100% cross browser compatible, so check the client
I used this solution to set the file name:
HTML:
Download!
<canvas id="canvas"></canvas>
JavaScript:
function download(){
document.getElementById("downloader").download = "image.png";
document.getElementById("downloader").href = document.getElementById("canvas").toDataURL("image/png").replace(/^data:image\/[^;]/, 'data:application/octet-stream');
}
I had this problem and this is the best solution without any external or additional script libraries:
In Javascript tags or file create this function:
We assume here that canvas is your canvas:
function download(){
var download = document.getElementById("download");
var image = document.getElementById("canvas").toDataURL("image/png")
.replace("image/png", "image/octet-stream");
download.setAttribute("href", image);
}
In the body part of your HTML specify the button:
<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>
This is working and download link looks like a button. Tested in Firefox and Chrome.
I maybe discovered a better way for not forcing the user to right click and "save image as". Live draw the canvas base64 code into the href of the link and modify it so the download will start automatically. I don't know if it's universally browser compatible, but it should work with the main/new browsers.
var canvas = document.getElementById('your-canvas');
if (canvas.getContext) {
var C = canvas.getContext('2d');
}
$('#your-canvas').mousedown(function(event) {
// feel free to choose your event ;)
// just for example
// var OFFSET = $(this).offset();
// var x = event.pageX - OFFSET.left;
// var y = event.pageY - OFFSET.top;
// standard data to url
var imgdata = canvas.toDataURL('image/png');
// modify the dataUrl so the browser starts downloading it instead of just showing it
var newdata = imgdata.replace(/^data:image\/png/,'data:application/octet-stream');
// give the link the values it needs
$('a.linkwithnewattr').attr('download','your_pic_name.png').attr('href',newdata);
});
You can wrap the <a> around anything you want.
Submit a form that contains an input with value of canvas toDataURL('image/png') e.g
//JAVASCRIPT
var canvas = document.getElementById("canvas");
var url = canvas.toDataUrl('image/png');
Insert the value of the url to your hidden input on form element.
//PHP
$data = $_POST['photo'];
$data = str_replace('data:image/png;base64,', '', $data);
$data = base64_decode($data);
file_put_contents("i". rand(0, 50).".png", $data);
Try this:
jQuery('body').after('<a id="Download" target="_blank">Click Here</a>');
var canvas = document.getElementById('canvasID');
var ctx = canvas.getContext('2d');
document.getElementById('Download').addEventListener('click', function() {
downloadCanvas(this, 'canvas', 'test.png');
}, false);
function downloadCanvas(link, canvasId, filename) {
link.href = document.getElementById(canvasId).toDataURL();
link.Download = filename;
}
You can just put this code in console in firefox or chrom and after changed your canvas tag ID in this above script and run this script in console.
After the execute this code you will see the link as text "click here" at bottom of the html page. click on this link and open the canvas drawing as a PNG image in new window save the image.
Full Working HTML Code. Cut+Paste into new .HTML file:
Contains Two Examples:
Canvas in HTML file.
Canvas dynamically created with Javascript.
Tested In:
Chrome
Internet Explorer
*Edge (title name does not show up)
Firefox
Opera
<!DOCTYPE HTML >
<html lang="en">
<head>
<meta charset="UTF-8">
<title> #SAVE_CANVAS_TEST# </title>
<meta
name ="author"
content="John Mark Isaac Madison"
>
<!-- EMAIL: J4M4I5M7 -[AT]- Hotmail.com -->
</head>
<body>
<div id="about_the_code">
Illustrates:
<ol>
<li>How to save a canvas from HTML page. </li>
<li>How to save a dynamically created canvas.</li>
</ol>
</div>
<canvas id="DOM_CANVAS"
width ="300"
height="300"
></canvas>
<div id="controls">
<button type="button" style="width:300px;"
onclick="obj.SAVE_CANVAS()">
SAVE_CANVAS ( Dynamically Made Canvas )
</button>
<button type="button" style="width:300px;"
onclick="obj.SAVE_CANVAS('DOM_CANVAS')">
SAVE_CANVAS ( Canvas In HTML Code )
</button>
</div>
<script>
var obj = new MyTestCodeClass();
function MyTestCodeClass(){
//Publically exposed functions:
this.SAVE_CANVAS = SAVE_CANVAS;
//:Private:
var _canvas;
var _canvas_id = "ID_OF_DYNAMIC_CANVAS";
var _name_hash_counter = 0;
//:Create Canvas:
(function _constructor(){
var D = document;
var CE = D.createElement.bind(D);
_canvas = CE("canvas");
_canvas.width = 300;
_canvas.height= 300;
_canvas.id = _canvas_id;
})();
//:Before saving the canvas, fill it so
//:we can see it. For demonstration of code.
function _fillCanvas(input_canvas, r,g,b){
var ctx = input_canvas.getContext("2d");
var c = input_canvas;
ctx.fillStyle = "rgb("+r+","+g+","+b+")";
ctx.fillRect(0, 0, c.width, c.height);
}
//:Saves canvas. If optional_id supplied,
//:will save canvas off the DOM. If not,
//:will save the dynamically created canvas.
function SAVE_CANVAS(optional_id){
var c = _getCanvas( optional_id );
//:Debug Code: Color canvas from DOM
//:green, internal canvas red.
if( optional_id ){
_fillCanvas(c,0,255,0);
}else{
_fillCanvas(c,255,0,0);
}
_saveCanvas( c );
}
//:If optional_id supplied, get canvas
//:from DOM. Else, get internal dynamically
//:created canvas.
function _getCanvas( optional_id ){
var c = null; //:canvas.
if( typeof optional_id == "string"){
var id = optional_id;
var d = document;
var c = d.getElementById( id );
}else{
c = _canvas;
}
return c;
}
function _saveCanvas( canvas ){
if(!window){ alert("[WINDOW_IS_NULL]"); }
//:We want to give the window a unique
//:name so that we can save multiple times
//:without having to close previous
//:windows.
_name_hash_counter++ ;
var NHC = _name_hash_counter ;
var URL = 'about:blank' ;
var name= 'UNIQUE_WINDOW_ID' + NHC;
var w=window.open( URL, name ) ;
if(!w){ alert("[W_IS_NULL]");}
//:Create the page contents,
//:THEN set the tile. Order Matters.
var DW = "" ;
DW += "<img src='" ;
DW += canvas.toDataURL("image/png");
DW += "' alt='from canvas'/>" ;
w.document.write(DW) ;
w.document.title = "NHC"+NHC ;
}
}//:end class
</script>
</body>
<!-- In IE: Script cannot be outside of body. -->
</html>
I really like Tovask's answer but it doesn't work due to the function having the name download (this answer explains why). I also don't see the point in replacing "data:image/..." with "data:application/...".
The following code has been tested in Chrome and Firefox and seems to work fine in both.
JavaScript:
function prepDownload(a, canvas, name) {
a.download = name
a.href = canvas.toDataURL()
}
HTML:
Download
<canvas id="canvasId"></canvas>
My solution via vue and async support
async downloadImage () {
const canvas = this.$refs.canvas
const blob = await new Promise(resolve => canvas.toBlob(resolve))
const downloadLink = document.createElement('a')
downloadLink.href = window.URL.createObjectURL(blob)
downloadLink.download = 'mycanvasimage.png'
downloadLink.click()
}
var canvasId = chart.id + '-canvas';
var canvasDownloadId = chart.id + '-download-canvas';
var canvasHtml = Ext.String.format('<canvas id="{0}" width="{1}" height="{2}"></canvas><a id="{3}"/>',
canvasId,
chart.getWidth(),
chart.getHeight(),
canvasDownloadId);
var canvasElement = reportBuilder.add({ html: canvasHtml });
var canvas = document.getElementById(canvasId);
var canvasDownload = document.getElementById(canvasDownloadId);
canvasDownload.href = chart.getImage().data;
canvasDownload.download = 'chart';
canvasDownload.click();

Categories