I am trying to load a simple image using javascript, for that I am using following code
function loadImage(src) {
var image = new Image;
image.onload = function() {
document.body.appendChild(image);
};
image.onerror = function() {
document.body.appendChild(document.createTextNode('\nError loading as image: ' + this.src));
};
image.src = src;
}
loadImage('http://www.linkedin.com/favicon.ico');
loadImage('http://www.facebook.com/favicon.ico');
Fiddle Link
The problem I am facing is whole thing working in chrome and firefox but not working in internet explorer. I am not much used to with javascript.
Any solutions ?
IE will not load an ICO image into the browser unless its contentType is image/x-icon.
I can confirm by looking at the network tab in Firefox that the contentType for the LinkedIn image is application/octet-stream which would explain why IE will not show it while the Facebook image has a content type of image/x-icon which IE likes.
There is nothing you can from the browser other than don't request an image that has that type set on its server. I'm quite sure that sites like LinkedIn will have other small images from there site that you can link to.
FYI, if you look at the linkedIn source for it's homepage, you will find a tag that points to http://s.c.lnkd.licdn.com/scds/common/u/images/logos/favicons/v1/16x16/favicon.ico which works just fine in IE (because it's an image/x-icon).
It is also worth noting that some older versions of IE (and to be honest, I don't recall if IE8 is one of the affected ones), the onload event is NOT fired of the image is loaded from cache.
function loadImage(src) {
function doOnLoad() {
document.body.appendChild(image);
}
var image = new Image;
image.onload = doOnLoad;
image.onerror = function() {
document.body.appendChild(document.createTextNode('\nError loading as image: ' + this.src));
};
image.src = src;
if (image.complete) {
doOnLoad();
}
}
call the function on window load :-
<script type="text/javascript">
function loadImage(src) {
var image = new Image;
image.onload = function() {
document.body.appendChild(image);
};
image.onerror = function() {
document.body.appendChild(document.createTextNode('\nError loading as image: ' + this.src));
};
image.src = src;
}
window.onload=loadImage('http://www.linkedin.com/favicon.ico');
</script>
the image is not loading, when you call the method after load all the elements then it will work.
Related
I need to check if an image URL is valid, which means that the image loads properly in the browser.
I've tried using this:
const src = "https://i.imgur.com/vXPYhT5.jpeg"
const img = new Image()
img.onload = () => console.log("valid image :)")
img.onerror = () => console.log("invalid image :(")
img.crossOrigin = "anonymous"
img.src = src
The problem is that the above code outputs "invalid image :(" in some mobile browsers e.g Safari, even when the image is valid.
To be more clear: the above code is not a cross browser solution for that problem.
Example of user agent this problem happened:
{
"userAgentInfo": {
"browserName": "Safari",
"browserVersion": "13.0.5",
"engineName": "AppleWebKit",
"engineVersion": "605.1.15",
"isBot": false,
"isMobile": true,
"os": "CPU iPhone OS 13_3_1 like Mac OS X",
"platform": "iPhone"
}
}
PS1: The image have all kind of CORS stuff enabled.
PS2: I can not see the error because its just a notification from the error tracker like Airbrake.nofity("Invalid image") on img.onerror.
According to Mozilla CDN: The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document.createElement('img').
See this link: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
I have also checked the functionality is not working in Opera on my macOs! However, it is working on all other browsers. see this link:
https://jsbin.com/hofitusoke/edit?html,js,console,output
Moreover, for Browser compatibility, it is mentioned for some opera for mobile the functionality is unknown!
some mobile browsers doesn't load image until it is place on DOM to reduce data consumption. So I don't have test device. But you can try this code.
function validateImageUrl(url) {
const image = document.createElement('img');
image.onload = () => { console.log("valid image :)") }
image.onerror = () => { console.log("invalid image :(") }
image.crossOrigin = "anonymous"
image.style.display = 'none';
document.body.appendChild(image);
image.src = url;
}
validateImageUrl('https://i.imgur.com/vXPYhT5.jpeg');
I am trying to convert a section of my site into a downloadable image.
Firstly I convert the html to a canvas using:
$(function() {
$("#download").click(function() {
html2canvas($("#the-grid"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
$("#saved").append(canvas);
$("#saved canvas").attr('id', 'scan');
}
});
Which works fine the canvas get generated and all look's good.
I then want to turn that into an image which I can use for thumbnails later but also initiate a download of the image.
To do so I complete the function like this.
$(function() {
$("#download").click(function() {
html2canvas($("#the-grid"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
$("#saved").append(canvas);
$("#saved canvas").attr('id', 'scan');
var c=document.getElementById("scan");
var d=c.toDataURL("image/png");
var w=window.open('about:blank','Download Mix');
w.document.write("<img src='"+d+"' alt='Custom Blend'/>");
}
});
But it doesn't work.
The error's I get are totally irrelevant.
I am an experienced developer but I'm pretty new to Jquery so any help would be appreciated.
UPDATE
Got it to work.
Create image like this
$(function () {
$("#download").click(function () {
html2canvas($("#the-grid"), {
onrendered: function (canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
$("#saved").append(canvas);
$("#saved canvas").attr('id', 'scan');
var image = canvas.toDataURL("image/png");
$("#saved").append("<img src='"+image+"' alt='Custom Blend'/>");
}
});
image html ends up looking like
<img src="data:image/png;base64,iVBORw0KGgoAAAANS..." alt="Custom Blend">
Maybe this can help you :
var image = canvas.toDataURL("image/png"); // build url of the image
window.location.href=image; //activate download
image = "<img src='"+image+"'/>"; // set canvas image as source
Here's how I did this (note, there's no way to download a file in Safari and set the filename without pinging a server):
First, you need to get the canvas as a png: var img = canvas.toDataUrl('image/png');
Then, you'll want to convert that dataURL to a blob. For a good way to do that, see this function.
Now you want to download that blob. This will work in all browsers but Safari:
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob, 'image.png');
} else {
var url = window.URL || window.webkitURL;
var objectURL = url.createObjectURL(blob);
var ele = $('<a target="_blank"></a>')
.hide()
.attr('download', 'image.png')
.attr('href', objectURL);
$('body').append(ele);
var clickEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false,
});
ele[0].dispatchEvent(clickEvent);
window.setTimeout(function() {
url.revokeObjectURL(objectURL);
ele.remove();
}, 1000);
}
This creates an invisible link and simulates a click on it. The click() function won't work in Firefox, so you have to create an event and dispatch it by hand. Finally, it does a bit of clean up by removing the invisible link after one second. In IE, it uses the method provided by Microsoft. This will download the image with the filename "image.png". It also has the benefit of being able to download any blob, if you need to be able to do more with your code. Hopefully this helps!
I have a problem. I am trying to draw an image onto a canvas. The image is not from the HTML page, but on a file. Here is the code i use:
var img = new Image();
img.src = "/images/logo.jpg";
this._canvas.drawImage(img, 300, 300);// this is line 14
now, here's the problem. This does not seem to work on Firefox and IE10 (I haven't tested yet on other browsers). On Firefox (21) I get:
[19:09:02.976] NS_ERROR_NOT_AVAILABLE: Component is not available # file:///D:/Watermellon/scripts/base-classes.js:14
and on IE10 i get:
SCRIPT16389: Unspecified error.
base-classes.js, line 14 character 13
The files and their directories are:
root/index.html
root/scripts/base-classes.js
root/images/logo.jpg
Now when I change the img.src to a URL (an image from another site) everything works fine, the image draws itself after a delay(for it's get from the url). What am I doing wrong?
I'm guessing the problem is that the image isn't loaded yet before you attempt to use it. Try this:
var img = new Image();
img.onload = function () {
this._canvas.drawImage(img, 300, 300);// this is line 14
};
img.src = "images/logo.jpg";
The src property is set after binding the event because a cached image's load event fires immediately (which is a common problem in IE).
And according to your structure, the path to the image would probably be images/logo.jpg (removing the first /)
You need to wait for the image to load before attempting to draw it into a canvas:
var img = new Image();
img.src = "/images/logo.jpg";
img.onload = function () {
this._canvas.drawImage(img, 300, 300);// this is line 14
}
The problem that I guess here, is when the resources be available?, but there is a way to confirm that the resources are available, just check 'complete' attribute of the image object.
if (img.complete == true){
// is available.
} else {
// wait until is ready.
}
Also, you can make a merge method with onload event and a delay method that checking both stuff.
var img = new Image();
//first attach handler
img.onload = function(e){
if (e.target.complete == true) {
yourHandler(e);
} else {
var maxTimes = 10;
var countTimes = 0;
function retryLoadImage() {
setTimeout(function () {
if (countTimes > maxTimes) {
// -- cannot load image.
return;
} else {
if (e.target.complete == true) {
yourHandler(e);
} else {
retryLoadImage();
}
}
countTimes++;
}, 50);
};
}
};
img.src = yourSource;
This is working for me!!! on IE and FF.
I have the following code :
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
document.write('<br><br><br>Image: <img src="'+pastedImage.src+'" height="700" width="700"/>');
}
pastedImage.src = source;
}
Here I am displaying the image through html image tag which I wrote in document.write and provide appropriate height and width to image.
My question is can it possible to displaying image into the canvas instead of html img tag? So that I can drag and crop that image as I want?
But how can I display it in canvas?
Further I want to implement save that image using PHP but for now let me know about previous issue.
Try This
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image(); // Create new img element
img.onload = function(){
// execute drawImage statements here This is essential as it waits till image is loaded before drawing it.
ctx.drawImage(img , 0, 0);
};
img.src = 'myImage.png'; // Set source path
Make sure the image is hosted in same domain as your site. Read this for Javascript Security Restrictions Same Origin Policy.
E.g. If your site is http://example.com/
then the Image should be hosted on http://example.com/../myImage.png
if you try http://facebook.com/..image/ or something then it will throw security error.
Use
CanvasRenderingContext2D.drawImage.
function createImage(source) {
var ctx = document.getElementById('canvas').getContext('2d');
var pastedImage = new Image();
pastedImage.onload = function(){
ctx.drawImage(pastedImage, 0, 0);
};
pastedImage = source;
}
Also MDN seems to be have nice examples.
I have the following simple preloading function which substitute an image "src" attribute with another image (an animated GIF "Loading"). The problem arises only in IE: if the "loading" GIF is smaller than the actual image src, that will be resized. For example if I have a square 100px image and preload it, the image is temporarly substituted by an animated GIF of 50x50px. Whem the original image is fully loaded it is NOT displayed at its size, but at the smaller 50px. Here is the code, if you need it
_preload = function(url, placeholderUrl) {
var img = new Image();
loading = true;
var placeholder = new Element("img", {
src: placeholderUrl
});
img.placeholder = placeholder;
img.onload = function(evt) {
this.placeholder.src = this.src;
loading = false;
}
img.src = url;
return placeholder;
}
Here you can see the visual error
You should be able to adjust the width/height of the image within the callback function:
img.onload = function(evt) {
this.placeholder.src = this.src;
this.placeholder.width = this.width;
this.placeholder.height = this.height;
loading = false;
}
Example: Resizing image onLoad
I guess replacing placeholder with img (the img-elements inside the dom), instead of simply changing the src-attribute of placeholder, should fix this issue.