Weird Image with SVG in src attribute in Edge browser - html

I'm rendering image and I'm passing svg file as source attribute to image. It works perfect on all browsers, except Edge. I cant find an reason why it renders this weird black box with cross:
Html code of is like: <img width="3029" height="3920" id="id_of_image" src="data:image/svg+xml;charset=utf-8,<svg xmlns=....................CONTENT OF SVG............></svg>"/>
How can I show this kind of image also on edge? I'm filling src attribute from JS where I have element as string. I need to put it into image attribute, but question is how is that possible?

Problem solved. Issue was that in Edge it had problem with rendering svg when you are using tags directly in attributes. So solution was to replace and convert string in JS. I created function to generate SVG attribute for image from ajax request, when you have your SVG string:
function fixSVGDiagram(svgString) {
svgString = svgString.replace("<![CDATA[", "").replace("]]>", ""); //If styles occured, Edge crashes on that
svgString = svgString.replace(/#/g,"temporaryhash") //Because of hasthag issues (in styles)
svgString = encodeURI(svgString) //Magic happens
svgString = svgString.replace(/temporaryhash/g, "%23") //Get back hashtag
return "data:image/svg+xml;charset=utf-8," + svgString
}
If you are loading SVG as attribute in ajax request then you can store it as string:
svgData = (new XMLSerializer).serializeToString(responseData);
and then
var img = new Image
img.src = fixSVGDiagram(svgData)
and you can put image where you want.

svg code doesn't work like this for svg image.
Without the use of image tag you can directly use the svg tag in the html code.
OR.
You can create an svg file with *.svg extension and set the filename as the src in the image attribute.

Related

Brower cache issue for animated GIF loader image [duplicate]

First time I view the page with an animated .gif it plays fine on page load (lasts about 2 secs).
On refresh (F5), the .gif no longer plays and only the last frame of gif animation is shown.
Is there anything I can do do to make sure it plays everytime?
For the PHP the much better option then using date("Ymdgis"); is using time(), like this:
<img src="picturePath.gif?<?php echo time();?>" />
Strange behavior that's affects every browser..
I usually refresh it manually with this script (it uses jQuery)
<img id="gif_animata" src="picturePath.gif">
<script type="text/javascript">
var gifSource = $('#gif_animata').attr('src'); //get the source in the var
$('#gif_animata').attr('src', ""); //erase the source
$('#gif_animata').attr('src', gifSource+"?"+new Date().getTime()); //add the date to the source of the image... :-)
</script>
This will refresh the src of the image adding the current date, so the browser will re-load it, thinking that's a new image.
Otherwise in PHP way (I prefer this one):
<img src="picturePath.gif?<?php echo date("Ymdgis");?>" />
//for the browser it will seems that's a new picture!
<img src="picturePath.gif?2012092011207">
The workaround that works for me for this issue is to reload the GIF manually using Javascript
GIF implemented on CSS (background-images)
var element = document.getElementById(name);
element.style.backgroundImage = "none";
element.style.backgroundImage = "url(imagepath.gif?"+new Date().getTime()+")";
GIF implemented on HTML (img tag)
var element = document.getElementById(name);
element.src = "";
element.src = "imagepath.gif?"+new Date().getTime();
Thanks to #sekmo
This works, only requires one line below it and I suggest not filling the <img> src attribute at first so the page doesn't try to load any unnecessary resources.
<img id="gif" src=""/>
<script>document.getElementById('gif').src="path_to_picture.gif?a="+Math.random()</script>
It could be that your browser is just showing the cached version. Try holding shift and refreshing, and see if it works.

Use an SVG image with non `.svg` extension in <img> tag

I'm trying to display an SVG in an <img> tag, but the SVG files don't have the .svg extension.
So a few things,
The file extension is not .svg, but the content within the file IS svg.
I need to use the <img> tag because it's important that I ignore the width and height in the SVG file (if any) and instead use the ones defined in my HTML/CSS. I cannot edit the contents of the SVG file, these are randomly uploaded and I don't want to be modifying them each time they are uploaded.
I can use PHP to read the data from the SVG, but it still needs to be displayed in the <img> tag.
Currently, when I try to use the SVG that has SVG content but no SVG file extension, it will act as though it couldn't load the image.
However, if I visit that same URL in my web browser, it will display the SVG fine regardless of the fact that it doesn't have a .svg extension.
<img src="https://di.community/uploads/monthly_2019_02/D-00023_svg.614976c7cefbcc2e89ab406b11f87800" />
How would I get the SVGs to display properly while still using the <img> tag to determine width/height, without modifying the SVG file and without an .svg extension.
I've tried the following, but the width/height is still used from the SVG and not the ones i define in HTML/CSS.
<span style='display: inline-block; margin: 0px; width: 35px !important; height: 35px !important;'>
<?php echo file_get_contents('https://di.community/uploads/monthly_2019_02/D-00023_svg.614976c7cefbcc2e89ab406b11f87800'); ?>
</span>
You can base-64 encode the text directly on the server and inject it directly into an image, or use the source as a remote reference.
<img src="data:image/svg+xml;base64,<?php echo PHP_BASE64_STRING ?>" />
<img src="https://di.community/uploads/monthly_2019_02/D-00023_svg.614976c7cefbcc2e89ab406b11f87800" />
The element's naturalWidth and naturalHeight properties will give the actual size of the image rather than the displayed/rendered size.
The script below will have the SVG data injected as-is into a block that shouldn't display.
HTML:
<script id="svgToCheck" type="script/no-execute">
<?php echo file_get_contents('https://di.community/uploads/monthly_2019_02/D-00023_svg.614976c7cefbcc2e89ab406b11f87800'); ?>
</script>
JS:
function getImageSizeFromUrl(url) {
return new Promise(function(resolve, reject) {
const image = document.createElement('img');
image.addEventListener('load', _ => resolve({ width: image.naturalWidth, height: image.naturalHeight }), false);
image.addEventListener('error', reject, false);
image.src = url;
}
}
// get the SVG
const svgText = document.getElementById("svgToCheck").innerHTML.trim();
// convert to data url
const svgUrl = `data:image/svg+xml;base64,${window.btoa(svgText)}`;
// get the size
getImageSizeFromUrl(svgUrl).then(size => console.log(size.width, size.height));
Use an <object> tag instead. It gives you the opportunity to state the MIME type directly. Sizing works just as with <img> tags.
<object type="image/svg+xml" data="myFile.extension"></object>

iframe with srcdoc: same-page links load the parent page in the frame

Same-page links work by referencing another element that has id="sec-id" on the same page, using
for instance. A link like this is relative.
However, if I use that very same syntax in the iframe in my LaTeX.js playground, it will not just scroll to the destination element, but (re)load the whole playground page inside the ifame. (Note that I set the contents of the iframe programmatically with iframe.srcdoc = html)
Example: LaTeX.js playground, right at the end of the first section click on the link in "See also SecĀ­tion 11." in the iframe on the right side.
What could be the reason?
UPDATE: I now understand the source of the problem: the browser uses the document's base URL to make all relative URLs absolute (see <base>). The trouble starts with an iframe that has its content set with srcdoc: no unique base URL is specified, and in that case the base URL of the parent frame/document is used--the playground in my case (see the HTML Standard).
Therefore, the question becomes: is there a way to reference the srcdoc iframe in a base URL? or is it possible to make the browser not prepend the base? or to make a base URL that doesn't change the relative #sec-id URLs?
I don't know exactly how you could resolve this, I think it is because the srcdoc, you can't use the src with the content-type because the character limit, but you can convert it to a Blob and it kinda works, the style are lost though. Maybe you can use it as a starting point, based on your page:
// Get the document content
const doc = document.querySelector('iframe').srcdoc;
// Convert it to blob
const blob = new Blob([doc], {type : 'text/html'});
// Load the blob on the src attr
document.querySelector('iframe').src = URL.createObjectURL(blob);
// Remove srcdoc to allow src
document.querySelector('iframe').removeAttribute('srcdoc');
What about catching the event and scrolling to the desired anchor?
$("a").click(function(e) {
$('.iframe').animate({
scrollTop: $(e.target.attr('href')).offset().top
}, 2000);
return false;
});
For the record, it seems that my question is not possible, i.e., it is not possible to use relative same-page links in an iframe that has its content set using srcdoc. A workaround has to be used, see the other answer.

Change image of an object

I want to make so that when I run a function it changes the image of objects in a function and I thought this would work
for(var i = 0; i < heads.length; i++){heads[i].src = ram_head;}
with ram_head equaling a string with the url but when I run the code the image does not change at all when I run the function.
Example of the code: http://jsfiddle.net/themagicalcake/URvA7
Here's code that:
creates an array of image objects (heads)
assigns the same image URL to all of those image objects (rams_head)
and when each image has fully loaded draws that image to the canvas.
Example code and a Demo: http://jsfiddle.net/m1erickson/5DXe7/
var ram_head="https://dl.dropboxusercontent.com/u/139992952/multple/RAMDISEGNO.jpg";
var heads=[];
heads.push(new Image());
heads.push(new Image());
for(var i=0;i<heads.length;i++){
heads[i].onload=function(){
ctx.drawImage(this,this.x,10);
}
heads[i].x=i*100;
heads[i].src=ram_head;
}
I see three issues with the code you've now linked to:
When you set the .src of an Image object, you can't use that image to draw with until the new .src URL image has loaded. If you want to change the .src and then draw, you have to handle the onload event and draw when that fires.
In your onkeydown handler, you are setting heads[i].src, but the image object is heads[i].img so the .src of the image would be heads[i].img.src.
Since you aren't displaying native <img> tags in the DOM, but are instead drawing the image yourself, after you change the .src of the image and then wait for that new image to load, if you want the image to display in your drawing context, you have to redraw it yourself. I won't just redraw just because you changed the .src.

How to set ContextPath for an image link

i am trying to put context path for an image in HTML.<img src="/MyWeb/images/pageSetup.gif">
Here /MyWeb is the ContextPath which is hardcoded. How can i get dynamically.
i am using as <img src=contextPath+"/images/pageSetup.gif">but image is not displaying. Is there any option.
First of all, "Context path" is a term which is typically used in JSP/Servlet web applications, but you didn't mention anything about it. Your question history however confirms that you're using JSP/Servlet. In the future, you should be telling and tagging what server side language you're using, because "plain HTML" doesn't have a concept of "variables" and "dynamic generation" at all. It are server side languages like JSP which have the capability of maintaining and accessing variables and dyamically generating HTML. JavaScript can be used, but it has its limitations as it runs in webbrowser, not in webserver.
The question as you initially have will only confuse answerers and yield completly unexpected answers. With question tags you reach a specific target group. If you use alone the [html] tag, you will get answers which assume that you're using pure/plain HTML without any server side language.
Back to your question: you can use ${pageContext.request.contextPath} for this.
<img src="${pageContext.request.contextPath}/images/pageSetup.gif">
See also:
How to use relative paths without including the context root name?
Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
You can't write JavaScript in the src attribute. To do what you want, try some code like this:
var img = new Image();
img.src = contextPath + "/images/pageSetup.gif";
document.getElementById('display').appendChild(img);
Here the target; the place where you want to display the image, is a div or span, with the id display.
Demo
With HTML, you'll have to take some extra traffic of producing an error, so you can replace the image, or you can send some traffic Google's way. Please do not use this:
<img src='notAnImage' onerror='this.src= contextPath + "/images/pageSetup.gif" '>
Demo
Do not use this.
You must use JavaScript for this.
First, have all images point to some dummy empty image on your domain while putting the real path as custom attribute:
<img src="empty.gif" real_src="/images/pageSetup.gif" />
Now have such JavaScript code in place to iterate over all the images and change their source to use the context path:
var contextPath = "/MyRealWeb";
window.onload = function() {
var images = document.getElementByTagName("img");
for (var i = 0; i < images.length; i++) {
var image = images[i];
var realSource = image.getAttribute("real_src") || "";
if (realSource.length > 0)
image.src = contextPath + realSource;
}
};