Why in Canvas(JS) toDataUrl() doesn't work after drawImage()? - javascript

<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = new Image();
img.onload = function(){
canvas.width=img.width;
canvas.height=img.height;
context.drawImage(img,0,0);
}
img.src="2.jpg";
function compress(){
var dataURL = canvas.toDataURL("image/jpg",0.5);
document.getElementById("img").src=dataURL;
}
setTimeout(compress,1000);
</script>
I've tried to use as example fillRect() instead of drawImage(). So it works normally... I'm sure that reason is drawImage()

If your image URL (the original URL, not the data URL) is from a different domain than that of the page where the code runs, then the canvas will be tainted when you draw the image to it, and you wont be able to get the pixels back out. That's a security measure. Thus if you're testing on jsfiddle and you're using http://placekitten.com/100/100 urls to test, it won't work.
Note that most modern browsers do not consider two file:// URLs to share a domain, so if you're running the test from local files, it won't work.

Related

Get pixel data back from programmatically generated image

I generate array of pixels in client side JavaScript code and convert it to a blob. Then I pass URL of the blob as image.src and revoke it at image.onload callback. I don't keep any references to the data, generated by the previous steps, so this data may be freed by GC.
There are many images generated this way, and it works fine. But sometimes user may want to save the generated image by clicking on a Save button near the image. I don't want to generate image again, because generation is slow, and the image is already generated and is visible on screen. So I want to get my pixels back from the image. I tried to create canvas again, draw image on it and then call toBlob, but browser treats this image as cross origin and throws an exception: "Failed to execute 'toBlob' on 'HTMLCanvasElement': tainted canvases may not be exported". Similar errors I get with canvas.toDataUrl and canvasContext.getImageData.
Is there a workaround for this problem?
I also tried to create canvases instead of images, but when I create the second canvas, the content of the first one clears.
Added
This error occurs only in the Chrome and other WebKit browsers. Firefox and MS Edge work fine. And when I commented out line of code that revoked blob url, this error disappeared - I can draw the image on the canvas and get its pixel data without CORS issues. But it is pointless to do so, because I already have blob that is not deleted.
But my page may generate many images - it depends on its user and is unlimited. Size of images is also unlimited - it may be useful to generate even 4096x4096 images. So I want to reduce memory consumption of my page as much as possible. And all these images should be downloadable. Generation of most images uses previously generated images, so to regenerate last image in a chain, I must to regenerate all images.
So I need a workaround only for Chrome browser.
Added 2
I tried to reproduce this problem in JS Fiddle, but couldn't. However locally my code doesn't work - I developed my app locally and I haven't tried running it on server. Create test.html file on your computer and open it in browser (locally, without server):
<html>
<body>
<pre id="log"></pre>
</body>
<script>
var log = document.getElementById("log");
var canvas = document.createElement("canvas");
canvas.width = canvas.height = 256;
var ctx = canvas.getContext("2d");
canvas.toBlob(function(blob) {
var img = new Image();
var blobUrl = URL.createObjectURL(blob);
img.src = blobUrl;
img.onload = function()
{
URL.revokeObjectURL(blobUrl);
ctx.drawImage(img, 0, 0);
try { canvas.toBlob(function(blob) { log.textContent += 'success\n'; }); }
catch(e) {log.textContent += e.message + '\n';}
};
});
</script>
</html>
It will print Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported..
So, I think, my workaround is to detect that page is run on combination of WebKit browser and file:/// protocol. And I can to defer revoking blob URL until page unload only for this combination.
That indeed sounds like a bug in chrome's implementation, you may want to report it.
What seems to happen is that chrome only checks if the image has been loaded through a clean origin when it is drawn for the first time on the canvas.
Since at this time, you already did revoke the blobURI, it can't map this URI to a clean origin (file:// protocol is quite strict on chrome).
But there seems to be a simple workaround:
By drawing this image on a [the reviver]* canvas before revoking the blobURI, chrome will mark the image as clean, and will remember it.
*[edit] Actually it seems it needs to be the same canvas...
So you can simply create your export canvas before-hand, and draw each images on it (to save memory you can even set it to 1x1px when you don't use it for the export) before you do revoke the image's src:
// somewhere accessible to the export logic
var reviver = document.createElement('canvas').getContext('2d');
// in your canvas to img logic
canvas.toBlob(function(blob){
var img = new Image();
img.onload = function(){
reviver.canvas.width = reviver.canvas.height = 1; // save memory
reviver.drawImage(this, 0,0); // mark our image as origin clean
URL.revokeObjectURL(this.src);
}
img.src = URL.createObjectURL(blob);
probablySaveInAnArray(img);
};
// and when you want to save your images to disk
function reviveBlob(img){
reviver.canvas.width = img.width;
reviver.canvas.height = img.height;
reviver.drawImage(img,0,0);
reviver.canvas.toBlob(...
}
But note that this method will create a new Blob, not retrieve the previous one, which has probably been Collected by the GarbageCollector at this time. But it is unfortunately your only way since you did revoke the blobURI...

Overlay two images to one img src [duplicate]

So I'm using google maps and I get the picture so it looks like this
<img id="staticMap"
src="http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap
&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318
&markers=color:red%7Ccolor:red%7Clabel:C%7C40.718217,-73.998284&sensor=false">
I need to save it. I have found this:
function getBase64FromImageUrl(URL) {
var img = new Image();
img.src = URL;
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
};
}
But I get this problem:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvases may not be exported.
I searched for fixes. I found a sample here How to use CORS but still I can't tie these 2 pieces of code together to make it work. Maybe I'm doing it the wrong way and there is a simpler way to do it? I'm trying to save this pic so that I can transfer the data to my server. So maybe someone did something like this and knows how to make .toDataURL() work as I need it?
Unless google serves this image with the correct Access-Control-Allow-Origin header, then you wont be able to use their image in canvas. This is due to not having CORS approval. You can read more about this here, but it essentially means:
Although you can use images without CORS approval in your canvas,
doing so taints the canvas. Once a canvas has been tainted, you can no
longer pull data back out of the canvas. For example, you can no
longer use the canvas toBlob(), toDataURL(), or getImageData()
methods; doing so will throw a security error.
This protects users from having private data exposed by using images
to pull information from remote web sites without permission.
I suggest just passing the URL to your server-side language and using curl to download the image. Be careful to sanitise this though!
EDIT:
As this answer is still the accepted answer, you should check out #shadyshrif's answer, which is to use:
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This will only work if you have the correct permissions, but will at least allow you to do what you want.
Just use the crossOrigin attribute and pass 'anonymous' as the second parameter
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This method will prevent you from getting an 'Access-Control-Allow-Origin' error from the server you are accessing to.
var img = new Image();
var timestamp = new Date().getTime();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url + '?' + timestamp;
Try the code below ...
<img crossOrigin="anonymous"
id="imgpicture"
fall-back="images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,
bungalow,high end luxury properties,landed properties,gated guarded house.png"
ng-src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
height="220"
width="200"
class="watermark">
In my case I was using the WebBrowser control (forcing IE 11) and I could not get past the error. Switching to CefSharp which uses Chrome solved it for me.
I had the same error message. I had the file in a simple .html, when I passed the file to php in Apache it worked
html2canvas(document.querySelector('#toPrint')).then(canvas => {
let pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
pdf.save(filename);
});
if the picture from the 3rd party site didn't set the header for cors ("access-control-allow-origin"), you can never download the picture file through chrome,
even if you use the setAttribute('crossOrigin', 'anonymous');
Here are some suggestions
hack chrome (use an extension, this will only work on your machine)
proxy the image through a service running on your site. The browser will see the domain as your site. This requires your service to request the image from the 3rd party.
By using fabric js we can solve this security error issue in IE.
function getBase64FromImageUrl(URL) {
var canvas = new fabric.Canvas('c');
var img = new Image();
img.onload = function() {
var canvas1 = document.createElement("canvas");
canvas1.width = this.width;
canvas1.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL({format: "png"});
};
img.src = URL;
}

why do not save pictures from the Canvas? [duplicate]

So I'm using google maps and I get the picture so it looks like this
<img id="staticMap"
src="http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap
&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318
&markers=color:red%7Ccolor:red%7Clabel:C%7C40.718217,-73.998284&sensor=false">
I need to save it. I have found this:
function getBase64FromImageUrl(URL) {
var img = new Image();
img.src = URL;
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
};
}
But I get this problem:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvases may not be exported.
I searched for fixes. I found a sample here How to use CORS but still I can't tie these 2 pieces of code together to make it work. Maybe I'm doing it the wrong way and there is a simpler way to do it? I'm trying to save this pic so that I can transfer the data to my server. So maybe someone did something like this and knows how to make .toDataURL() work as I need it?
Unless google serves this image with the correct Access-Control-Allow-Origin header, then you wont be able to use their image in canvas. This is due to not having CORS approval. You can read more about this here, but it essentially means:
Although you can use images without CORS approval in your canvas,
doing so taints the canvas. Once a canvas has been tainted, you can no
longer pull data back out of the canvas. For example, you can no
longer use the canvas toBlob(), toDataURL(), or getImageData()
methods; doing so will throw a security error.
This protects users from having private data exposed by using images
to pull information from remote web sites without permission.
I suggest just passing the URL to your server-side language and using curl to download the image. Be careful to sanitise this though!
EDIT:
As this answer is still the accepted answer, you should check out #shadyshrif's answer, which is to use:
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This will only work if you have the correct permissions, but will at least allow you to do what you want.
Just use the crossOrigin attribute and pass 'anonymous' as the second parameter
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This method will prevent you from getting an 'Access-Control-Allow-Origin' error from the server you are accessing to.
var img = new Image();
var timestamp = new Date().getTime();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url + '?' + timestamp;
Try the code below ...
<img crossOrigin="anonymous"
id="imgpicture"
fall-back="images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,
bungalow,high end luxury properties,landed properties,gated guarded house.png"
ng-src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
height="220"
width="200"
class="watermark">
In my case I was using the WebBrowser control (forcing IE 11) and I could not get past the error. Switching to CefSharp which uses Chrome solved it for me.
I had the same error message. I had the file in a simple .html, when I passed the file to php in Apache it worked
html2canvas(document.querySelector('#toPrint')).then(canvas => {
let pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
pdf.save(filename);
});
if the picture from the 3rd party site didn't set the header for cors ("access-control-allow-origin"), you can never download the picture file through chrome,
even if you use the setAttribute('crossOrigin', 'anonymous');
Here are some suggestions
hack chrome (use an extension, this will only work on your machine)
proxy the image through a service running on your site. The browser will see the domain as your site. This requires your service to request the image from the 3rd party.
By using fabric js we can solve this security error issue in IE.
function getBase64FromImageUrl(URL) {
var canvas = new fabric.Canvas('c');
var img = new Image();
img.onload = function() {
var canvas1 = document.createElement("canvas");
canvas1.width = this.width;
canvas1.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL({format: "png"});
};
img.src = URL;
}

How to draw an inline svg (in DOM) to a canvas?

Well, I need some help about convert .svg file/image to .png file/image...
I have a .svg image displayed on my page. It is saved on my server (as a .png file). I need to convert it to a .png file on demand (on click on a button) and save the .png file on the server (I will do this with an .ajax request).
But the problem is the conversion.
I read many things about the html5 Canvas, which can probably help doing what I need to do now, but I can't find any clear solution to my problem, and, tbh, I do not understand everything I found... So I need some clear advices/help about the way I have to do it.
Here is the "html idea" template :
<html>
<body>
<svg id="mySvg" width="300px" height="300px">
<!-- my svg data -->
</svg>
<label id="button">Click to convert</label>
<canvas id="myCanvas"></canvas>
</body>
</html>
and some js :
<script>
$("body").on("click","#button",function(){
var svgText = $("#myViewer").outerHTML;
var myCanvas = document.getElementById("canvas");
var ctxt = myCanvas.getContext("2d");
});
</script>
Then, I need to draw the svg into the Canvas, get back the base64 data, and save it in a .png file on my server... but... how? I read about so many different solutions that I'm actually... lost... I'm working on a jsfiddle, but I'm actually... nowhere... http://jsfiddle.net/xfh7nctk/6/ ... Thanks for reading / help
For inline SVG you'll need to:
Convert the SVG string to a Blob
Get an URL for the Blob
Create an image element and set the URL as src
When loaded (onload) you can draw the SVG as an image on canvas
Use toDataURL() to get the PNG file from canvas.
For example:
function drawInlineSVG(ctx, rawSVG, callback) {
var svg = new Blob([rawSVG], {type:"image/svg+xml;charset=utf-8"}),
domURL = self.URL || self.webkitURL || self,
url = domURL.createObjectURL(svg),
img = new Image;
img.onload = function () {
ctx.drawImage(this, 0, 0);
domURL.revokeObjectURL(url);
callback(this);
};
img.src = url;
}
// usage:
drawInlineSVG(ctxt, svgText, function() {
console.log(canvas.toDataURL()); // -> PNG data-uri
});
Of course, console.log here is just for example. Store/transfer the string instead here. (I would also recommend adding an onerror handler inside the method).
Also remember to set canvas size using either the width and height attributes, or from JavaScript using properties.
I come long after since some other question raised from this one because the accepted answer may produce undesirable behavior.
#K3N solution is almost right, but I would go against the use of svgElement.outerHTML.
Instead, one should prefer new XMLSerializer().serializeToString(svgElement).
Also, the use of blob and of the URL API is not necessary and a simple dataURI has more compatibility accross browsers.
So a complete version of this would be :
function drawInlineSVG(svgElement, ctx, callback) {
var svgURL = new XMLSerializer().serializeToString(svgElement);
var img = new Image();
img.onload = function() {
ctx.drawImage(this, 0, 0);
callback();
}
img.src = 'data:image/svg+xml; charset=utf8, ' + encodeURIComponent(svgURL);
}
// usage:
drawInlineSVG(document.querySelector('svg'), ctxt, function() {
console.log(canvas.toDataURL())
});

canvas.toDataURL() SecurityError

So I'm using google maps and I get the picture so it looks like this
<img id="staticMap"
src="http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap
&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318
&markers=color:red%7Ccolor:red%7Clabel:C%7C40.718217,-73.998284&sensor=false">
I need to save it. I have found this:
function getBase64FromImageUrl(URL) {
var img = new Image();
img.src = URL;
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
};
}
But I get this problem:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvases may not be exported.
I searched for fixes. I found a sample here How to use CORS but still I can't tie these 2 pieces of code together to make it work. Maybe I'm doing it the wrong way and there is a simpler way to do it? I'm trying to save this pic so that I can transfer the data to my server. So maybe someone did something like this and knows how to make .toDataURL() work as I need it?
Unless google serves this image with the correct Access-Control-Allow-Origin header, then you wont be able to use their image in canvas. This is due to not having CORS approval. You can read more about this here, but it essentially means:
Although you can use images without CORS approval in your canvas,
doing so taints the canvas. Once a canvas has been tainted, you can no
longer pull data back out of the canvas. For example, you can no
longer use the canvas toBlob(), toDataURL(), or getImageData()
methods; doing so will throw a security error.
This protects users from having private data exposed by using images
to pull information from remote web sites without permission.
I suggest just passing the URL to your server-side language and using curl to download the image. Be careful to sanitise this though!
EDIT:
As this answer is still the accepted answer, you should check out #shadyshrif's answer, which is to use:
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This will only work if you have the correct permissions, but will at least allow you to do what you want.
Just use the crossOrigin attribute and pass 'anonymous' as the second parameter
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This method will prevent you from getting an 'Access-Control-Allow-Origin' error from the server you are accessing to.
var img = new Image();
var timestamp = new Date().getTime();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url + '?' + timestamp;
Try the code below ...
<img crossOrigin="anonymous"
id="imgpicture"
fall-back="images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,
bungalow,high end luxury properties,landed properties,gated guarded house.png"
ng-src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
height="220"
width="200"
class="watermark">
In my case I was using the WebBrowser control (forcing IE 11) and I could not get past the error. Switching to CefSharp which uses Chrome solved it for me.
I had the same error message. I had the file in a simple .html, when I passed the file to php in Apache it worked
html2canvas(document.querySelector('#toPrint')).then(canvas => {
let pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
pdf.save(filename);
});
if the picture from the 3rd party site didn't set the header for cors ("access-control-allow-origin"), you can never download the picture file through chrome,
even if you use the setAttribute('crossOrigin', 'anonymous');
Here are some suggestions
hack chrome (use an extension, this will only work on your machine)
proxy the image through a service running on your site. The browser will see the domain as your site. This requires your service to request the image from the 3rd party.
By using fabric js we can solve this security error issue in IE.
function getBase64FromImageUrl(URL) {
var canvas = new fabric.Canvas('c');
var img = new Image();
img.onload = function() {
var canvas1 = document.createElement("canvas");
canvas1.width = this.width;
canvas1.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL({format: "png"});
};
img.src = URL;
}

Categories