So I'm trying to create a print map function for an OpenLayers 3 application I'm building. I'm aware of their example but whenever I attempt to use it I run into the dreaded tainted canvas issue. I've read the whole internet and come across folks saying first to set CORS correctly (done and done) but also to do:
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
The above is described here.
My question is, I've never really used toDataURL() before and I'm not really sure how I make sure the image being created has the crossOrigin attribute correctly set before it slams into the:
Error: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
Any thoughts?
I have seen this. My question is how they incorporate that into a function that works. Something like:
var printMap = function(){
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
img.onload = function() {
var canvas = document.getElementsByTagName('canvas');
var dataURL = canvas.toDataURL("image/png");
console.log(dataURL);
};
};
If the crossOrigin property/attribute is supported by the browser (it is now in FF, Chrome, latest Safari and Edge ), but the server doesn't answer with the proper headers (Access-Control-Allow-Origin: *), then the img's onerror event fires.
So we can just handle this event and remove the attribute if we want to draw the image anyway.
For browsers that don't handle this attribute, the only way o test if the canvas is tainted is to call the toDataURL into a try catch block.
Here is an example :
var urls =
["http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png",
"http://lorempixel.com/200/200"];
var tainted = false;
var img = new Image();
img.crossOrigin = 'anonymous';
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
var load_handler = function() {
canvas.width = 200;
canvas.height = 200;
ctx.fillStyle = 'white';
ctx.font = '15px sans-serif';
ctx.drawImage(this, 0, 0, 200, 200*(this.height/this.width));
// for browsers supporting the crossOrigin attribute
if (tainted) {
ctx.strokeText('canvas tainted', 20, 100);
ctx.fillText('canvas tainted', 20, 100);
} else {
// for others
try {
canvas.toDataURL();
} catch (e) {
tainted = true;
ctx.strokeText('canvas tainted after try catch', 20, 100);
ctx.fillText('canvas tainted after try catch', 20, 100);
}
}
};
var error_handler = function() {
// remove this onerror listener to avoid an infinite loop
this.onerror = function() {
return false
};
// certainly that the canvas was tainted
tainted = true;
// we need to removeAttribute() since chrome doesn't like the property=undefined way...
this.removeAttribute('crossorigin');
this.src = this.src;
};
img.onload = load_handler;
img.onerror = error_handler;
img.src = urls[0];
btn.onclick = function() {
// reset the flag
tainted = false;
// we need to create a new canvas, or it will keep its marked as tainted flag
// try to comment the 3 next lines and switch multiple times the src to see what I mean
ctx = canvas.cloneNode(true).getContext('2d');
canvas.parentNode.replaceChild(ctx.canvas, canvas);
canvas = ctx.canvas;
// reset the attributes and error handler
img.crossOrigin = 'anonymous';
img.onerror = error_handler;
img.src = urls[+!urls.indexOf(img.src)];
};
<button id="btn"> change image src </button><br>
But since toDataURL can be a really heavy call for just a check and that code in try catch is deoptimized, a better alternative for older browsers is to create a 1px*1px tester canvas, draw the images on it first and call its toDataURL in the try-catch block :
var urls = ["http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png", "http://lorempixel.com/200/200"];
var img = new Image();
img.crossOrigin = 'anonymous';
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
//create a canvas only for testing if our images will taint our canvas or not;
var taintTester = document.createElement('canvas').getContext('2d');
taintTester.width = 1;
taintTester.height = 1;
var load_handler = function() {
// our image flag
var willTaint = false;
// first draw on the tester
taintTester.drawImage(this, 0, 0);
// since it's only one pixel wide, toDataURL is way faster
try {
taintTester.canvas.toDataURL();
} catch (e) {
// update our flag
willTaint = true;
}
// it will taint the canvas
if (willTaint) {
// reset our tester
taintTester = taintTester.canvas.cloneNode(1).getContext('2d');
// do something
ctx.fillStyle = 'rgba(0,0,0,.7)';
ctx.fillRect(0, 75, ctx.measureText('we won\'t diplay ' + this.src).width + 40, 60);
ctx.fillStyle = 'white';
ctx.font = '15px sans-serif';
ctx.fillText('we won\'t diplay ' + this.src, 20, 100);
ctx.fillText('canvas would have been tainted', 20, 120);
} else {
// all clear
canvas.width = this.width;
canvas.height = this.height;
ctx.fillStyle = 'white';
ctx.font = '15px sans-serif';
ctx.drawImage(this, 0, 0);
}
};
var error_handler = function() {
// remove this onerror listener to avoid an infinite loop
this.onerror = function() {
return false
};
// we need to removeAttribute() since chrome doesn't like the property=undefined way...
this.removeAttribute('crossorigin');
this.src = this.src;
};
img.onload = load_handler;
img.onerror = error_handler;
img.src = urls[0];
btn.onclick = function() {
// reset the attributes and error handler
img.crossOrigin = 'anonymous';
img.onerror = error_handler;
img.src = urls[+!urls.indexOf(img.src)];
};
<button id="btn">change image src</button>
Note
Cross-origin requests are not the only way to taint a canvas :
In IE < Edge, drawing an svg on the canvas will taint the canvas for security issues, in the same way, latest Safari does taint the canvas if a <foreignObject> is present in an svg drawn onto the canvas and last, any UA will taint the canvas if an other tainted canvas is painted to it.
So the only solution in those cases to check if the canvas is tainted is to try-catch, and the best is to do so on a 1px by 1px test canvas.
So Pointy and Kaiido both had valid ways of making this work but they both missed that this was an OpenLayers issue (and in the case of Pointy, not a duplicate question).
The answer was to do this:
source = new ol.source.TileWMS({
crossOrigin: 'anonymous'
});
Basically you had to tell the map AND the layers that you wanted crossOrigin: anonymous. Otherwise your canvas would still be tainted. The more you know!
Related
So I was trying to draw animgin a canvas I tried everything but in the console it says img is not a property or something like that I don't remember so can anyone help?
Here's the js
function setupcanvas() {
var canvas = document.querySelector('canvas')
var c = canvas.getContext("2d")
c.beginPath();
var img = new image()
img.src = "flappy_bird_bird.png"
img.onload = function(){
c.drawImage(img, 100, 100)
}
}
Edit
Thx to mhkanfer "sorry if the name is wrong" I fixed it
You were mostly right, though their are a couple of things:
Make sure Image() is capitalized
Make sure your image src file actually exists in that directory
And make sure your canvas has a width and height, if you haven't specified that anywhere, you canvas wont be shown
If you were to revise this, it would look something like:
function setupcanvas() {
var canvas = document.querySelector('canvas')
var c = canvas.getContext("2d")
canvas.width = canvas.height = 200;
var img = new Image()
img.src = "example.png"
img.onload = function(){
c.drawImage(img, 0, 0)
}
}
I'm trying to use the Incode functionality to resize an image in LogicApps.
I'm not sure if this is possible with the absence of HTML.
var inputImage = workflowContext.actions.GetFileContent.outputs.body.$content;
function resize_image(imagesrc)
{
let image = new Image();
var base = "data:image/png;base64,";
image.src = base.concat(imagesrc);
image.onload = () => {
let width = image.width;
let height = image.height;
let canvas = document.createElement('canvas');
canvas.width = newWidth ;
canvas.height = newHeight;
let context = canvas.getContext('2d');
context.drawImage(image, 450, 0, newWidth-500, newHeight);
}
return image;
}
return resize_image(inputImage);
The error I receive
The inline code action 'JavaScriptCode' execution failed, with error 'Image is not defined'.
$content is the image in Base64, for example, starts like this:
iVBORw0KGgoAAAANSUhEUgAACFwAAAMMCAYAAABkSiF3...
Inline code can only perform some simple JavaScript operations, it may not be able to install canvas.
You can create an Azure Function App to resize your image.
For more details, you can refer to Call functions from Azure Logic Apps.
I'm currently making a Word Web Add-in.
This uses Internet Explorer as engine.
My Add-in needs to load multiple selected images from the users computer.
Because some of the selected images might be quite big, I resize them using HTML5 canvas. This is my code to resize:
function makeSmallImage(imageContainer, retries)
{
if (retries === undefined)
retries = 0;
console.log('Resizing image..')
return new Promise(function (resolve, reject)
{
img = img || new Image();
img.onload = function ()
{
// calculate new size
var width = 200;
var height = Math.floor((width / img.naturalWidth) * img.naturalHeight);
console.log('new size', width, height);
try
{
// create an off-screen canvas
canvas = canvas || document.createElement('canvas'),
ctx = ctx || canvas.getContext('2d');
// antialiasing
ctx.imageSmoothingEnabled = true;
// set its dimension to target size
canvas.width = width;
canvas.height = height;
// draw source image into the off-screen canvas:
ctx.drawImage(img, 0, 0, width, height);
// clean up
imageContainer.largeData = undefined;
if (img.src.substr(0, 4) === 'blob')
URL.revokeObjectURL(img.src);
img.src = '';
// encode image to data-uri with base64 version of compressed image
var newDataUri = canvas.toDataURL();
ctx.clearRect(0, 0, canvas.width, canvas.height);
console.log('Image resized!');
imageContainer.resizedData = newDataUri;
resolve(imageContainer);
}
catch (e)
{
if (img.src !== undefined && img.src.substr(0, 4) === 'blob')
URL.revokeObjectURL(img.src);
console.log(e);
if (e.message === "Unspecified error." && retries < 5)
{
setTimeout(function (imgContainer, re)
{
makeSmallImage(imgContainer, re).then(resolve).catch(reject);
}, 2000, imageContainer, retries + 1);
}
else
reject('There was an error while trying to resize one of the images!');
}
};
try
{
var blob = new Blob([imageContainer.largeData]);
img.src = URL.createObjectURL(blob);
} catch (e)
{
reject(e);
}
});
}
'img', 'canvas' and 'ctx' are global variables, so the same elements are reused.
'imgcontainer.largedata' is an uint8array. To avoid a lot of memory usage i'm loading and resizing the images one by one.
Despite of that, after loading for example 120 images of 10mb, it might happen that I get an error:
Unable to decode image at URL:
'blob:D5EFA3E0-EDE2-47E8-A91E-EAEAD97324F6'
I then get an exception "Unspecified error", with not a lot more info.
You can see in the code now that I added a litle mechanism to try again, but all new attempts fail.
I think the reason is that internet explorer is using too much memory. I think some resources are not being cleaned up correctly, but I can't seem to spot a memory leak in my code here (if you can, please let me know).
Does anybody have an idea of how I could fix this, or work around this?
if you try to resize the image, why not directly use the office APIs? you can first get the images, then use the height/width property to resize it, such as
image1.height = 5; image1.width = 5;
I am drawing on the canvas each time a user presses a button, however sometimes the image is not getting drawn on the canvas. I think this could be that the image isn't loaded in time before the context.drawimage function runs, as some of the smaller files sometimes get drawn. I've used the console and checked resources and so this is the only problem I can think of.
How do I avoid this problem?
This is my Javascript code.
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var questionbg = new Image();
var answerbg = new Image();
//this code is inside a function that is called each time a user presses a button
if(questiontype == "text"){
questionbg.src = "./resources/textquestionbg.png";
context.drawImage(questionbg, 0, 0);
}
//if image question
else if(questiontype == "image"){
questionbg.src = "./resources/imageaudiovideoquestionbg.png";
context.drawImage(questionbg, 0, 0);
}
//if audio question
else if(questiontype == "audio"){
questionbg.src = "./resources/imageaudiovideoquestionbg.png";
context.drawImage(questionbg, 0, 0);
}
//else it is a video question
else{
questionbg.src = "./resources/imageaudiovideoquestionbg.png";
context.drawImage(questionbg, 0, 0);
}
You should check if the image is loaded. If not then listen to the load event.
questionbg.src = "./resources/imageaudiovideoquestionbg.png";
if (questionbg.complete) {
context.drawImage(questionbg, 0, 0);
} else {
questionbg.onload = function () {
context.drawImage(questionbg, 0, 0);
};
}
MDN (Mozilla Doc, great source btw) suggests:
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
ctx.beginPath();
ctx.moveTo(30,96);
ctx.lineTo(70,66);
ctx.lineTo(103,76);
ctx.lineTo(170,15);
ctx.stroke();
};
img.src = '/files/4531/backdrop.png';
}
Obviously, you are not wanting to apply the stroke or fill. However, the idea is the same.
I want to use canvas to make an image to grayscale. There are a number of examples. But it has problem with my latest Chrome and Firefox. Surprisingly, IE9 is good. Is it the problem of my code?
And here is my code:
function draw() {
canvas = document.getElementById('canvas')
ctx = canvas.getContext('2d');
image = new Image();
image.src = 'ichiro.jpg';
ctx.drawImage(image, 0, 0);
imgd = ctx.getImageData(0, 0, 480, 400);
for (i=0; i<imgd.data.length; i+=4) {
grays = imgd.data[i]*.3 + imgd.data[i+1]*.6 + imgd.data[i+2]*.1;
imgd.data[i ] = grays; // red
imgd.data[i+1] = grays; // green
imgd.data[i+2] = grays; // blue
}
ctx.putImageData(imgd, 0, 0);
imggray = new Image();
imggray.src = canvas.toDataURL();
imggray.onload = function() {
ctx.drawImage(imggray, 0, 0);
}
}
I am new to HTML5 and javascript. So any help will be appreciated.
EDIT:
Sorry, I misread your question. It is almost certainly because of a security error. You are not allowed to use getImageData if you have drawn an image to the canvas that is from a different "origin" (a different domain or from your local file system). In Chrome locally you can get around it if you do:
C:\Users\root\AppData\Local\Google\Chrome\Application\chrome.exe --allow-file-access-from-files
There's something called the origin-clean flag and it is removed once you drawImage from a different origin. All files are of a different origin for (good) security reasons.
Original answer:
You need to wait for image to load:
working example: http://jsfiddle.net/SYLW2/1107/
...
// this now happens only after the image is loaded:
image.onload = function() {
ctx.drawImage(image, 0, 0);
imgd = ctx.getImageData(0, 0, 480, 400);
for (i=0; i<imgd.data.length; i+=4) {
grays = imgd.data[i]*.3 + imgd.data[i+1]*.6 + imgd.data[i+2]*.1;
imgd.data[i ] = grays; // red
imgd.data[i+1] = grays; // green
imgd.data[i+2] = grays; // blue
}
ctx.putImageData(imgd, 0, 0);
imggray = new Image();
imggray.src = canvas.toDataURL();
imggray.onload = function() {
ctx.drawImage(imggray, 0, 0);
}
}
image.src = 'http://placekitten.com/400/400';