How to get GIFs "out of sync" - html

I'm trying to reliably load the same GIF, but have it play at different times.
Overall, I expected to find a spec that would tell me what the rules were for rendering (i.e. what's in sync what's out of sync), but I haven't been able to find any such standard. Is there any spec for how GIFs are rendered with respect to timing?
Consider these examples:
https://i.stack.imgur.com/LwWBD.gif
https://i.stack.imgur.com/LwWBD.gif?blah=1
https://i.stack.imgur.com/3As1l.gif
Safari, seems to keep everything in sync regardless of the URL. Chrome on the initial load has the timings separate by URL, but eventually has them in sync. Firefox seems to depend solely on the URL without any parameters to determine syncing.
Any insight would be appreciated.

Tested on Chrome, abney317's answer works for me. I was able to get staggered start times by adding a query string to the end of the URL.
const image = document.querySelector('img');
img.src = imgUrl + '?id=' + Math.floor(Math.random() * 100);

Related

Why does Firefox produce larger WebM video files compared with Chrome?

I and my team have been struggling lately to find an explanation why does Firefox produce larger WebM/VP8 video files compared with Chrome when using the MediaRecorder API in our project.
In short, we record a MediaStream from a HTMLCanvas via the captureStream method. In attempt to isolate everything from our app that might affect this, I developed a small dedicated test app which records a <canvas> and produces WebM files. I've been performing tests with the same footage, video duration, codec, A/V bit rate and frame rate. However, Firefox still ends up creating up to 4 times larger files compared with Chrome. I also tried using a different MediaStream source like the web camera but the results were similar.
Here is a fiddle which should demonstrate what I am talking about: https://jsfiddle.net/nzwasv8k/1/ https://jsfiddle.net/f2upgs8j/3/.
You can try recording 10-sec or 20-sec long videos on both FF and Chrome, and notice the difference between the file sizes. Note that I am using only 4 relatively simple frames/images in this demo. In real-world usage, like in our app where we record a video stream of a desktop, we reached the staggering 9 times difference.
I am not a video codec guru in any way but I believe that the browsers should follow the same specifications when implementing a certain technology; therefore, such a tremendous difference shouldn't occur, I guess. Considering my knowledge is limited, I cannot conclude whether this is a bug or something totally expected. This is why, I am addressing the question here since my research on the topic, so far, led to absolutely nothing. I'll be really glad, if someone can point what is the logical explanation behind it. Thanks in advance!
Because they don't use the same settings...
The webm encoder has a lot of other params than the ones we've got access to from the MediaRecorder.
These params may all have an influence on the output file's size, and are up to implementors to set.
Here are snapshots I took of the videos generated from your updated fiddle [click to enlarge]:
Chrome 1
Firefox 1
Chrome 2
Firefox 2
I hope you can appreciate the difference of quality, it's about the same as between webp's 0.15 vs 0.8 quality params, and the sizes also reflects these changes.
const supportWebPExport = document.createElement('canvas').toDataURL('image/webp').indexOf('webp') > -1;
const mime = supportWebPExport ? 'image/webp' : 'image/jpeg';
const img = new Image();
img.onload = doit;
img.crossOrigin = 'anonymous';
img.src = "https://i.imgur.com/gwytj0N.jpg";
function doit() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = this.width,
canvas.height = this.height;
ctx.drawImage(this, 0,0);
canvas.toBlob(b => appendToDoc(b, '0.15'), mime, 0.15);
canvas.toBlob(b => appendToDoc(b, '0.8'),mime, 0.8);
}
function appendToDoc(blob, qual) {
const p = document.createElement('p');
p.textContent = `quality: ${qual} size: ${blob.size/1000}kb`;
p.appendChild(new Image).src = URL.createObjectURL(blob);
document.body.appendChild(p);
}
So yes, that's how it is... One way or the other could be better for your cases, but the best would be that we, web-devs, get access to these parameters. Unfortunately, this is not an easy thing to do from the specs point-of-view...

Unexpected CORS issue for normal images in Chrome and iOS Safari

I'm facing a CORS issue that is driving me insane. Allow me to share an example URL:
http://www.jungledragon.com/image/19905/mature_female_eastern_forktail.html/zoom
As the issue can only be reproduced once per page, here is a list of other images:
http://www.jungledragon.com/all/recent
From that overview, you can open any photo page. Next, from that photo page click the image once more to launch it fullscreen, as that is where the issue lies.
Now allow me to explain the setup, and the problem. The site itself is hosted on a Linux server within my control. The site is at www.jungledragon.com. The images, however, are stored at Amazon S3, where the image bucket has an alias of media.jungledragon.com.
The basic situation is simple:
<div id="slideshow-image-container">
<div class="slideshow-image-wrapper">
<img src="http://media.jungledragon.com/images/1755/19907_large.jpg?AWSAccessKeyId=05GMT0V3GWVNE7GGM1R2&Expires=1409788810&Signature=QH26XDrVuhyr1Qimd7IOBsnui5s%3D" id="19907" class="img-slideshow img-sec wide" data-constrained="true" data-maxheight="2056" crossorigin="anonymous">
</div>
</div>
As you can see, I'm just using the normal 'html' way of loading an image. The image URL is signed and can time out, but that shouldn't be relevant. It is my understanding that CORS does not apply to this situation, since loading images from an external domain this way has been supported for decades. The image is not loaded using javascript, after all.
Just to be sure though, the crossorigin attribute is set in HTML. Furthermore, as a way of testing, I have set a very liberal CORS policy on the image bucket:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>PUT</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Content-Type</AllowedHeader>
<AllowedHeader>x-amz-acl</AllowedHeader>
<AllowedHeader>origin</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Now, the situation gets a bit more complicated. The fullscreen image viewer is supposed to get a background color that is the dominant/average color of the actual image on screen. That color is calculated using canvas, yet it is only calculated once. The first time it is calculated for that image, the result is communicated to the back-end using an ajax call and then stored forever. Subsequent visits to the image will not run the calculation logic again, it will simply set the background color of the body element and all is good.
Here is the logic that does the calculation:
<script>
$( document ).ready(function() {
<?php if (!$bigimage['dominantcolor']) { ?>
$('#<?= $bigimage['image_id'] ?>').load(function(){
var rgb = getAverageRGB(document.getElementById('<?= $bigimage['image_id'] ?>'));
document.body.style.backgroundColor = 'rgb('+rgb.r+','+rgb.g+','+rgb.b+')';
if (rgb!==false) {
$.get(basepath + "image/<?= $bigimage['image_id'] ?>/setcolor/" + rgb.r + "-" + rgb.g + "-" + rgb.b);
}
});
<?php } ?>
});
Yes, I'm mixing in back-end code with front-end code. The above code says that if we do not yet know the dominant color in the scene, calculate it. The load function is used because at document ready, the actual image from the normal html may not have been loaded completely. Next, if the dominant color is not known yet, and the image is loaded, we trigger the function that calculates the dominant color. Here it is:
function getAverageRGB(imgEl) {
var blockSize = 5, // only visit every 5 pixels
defaultRGB = {r:0,g:0,b:0}, // for non-supporting envs
canvas = document.createElement('canvas'),
context = canvas.getContext && canvas.getContext('2d'),
data, width, height,
i = -4,
length,
rgb = {r:0,g:0,b:0},
count = 0;
if (!context) {
return defaultRGB;
}
height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;
imgEl.crossOrigin = "anonymous";
context.drawImage(imgEl, 0, 0);
try {
data = context.getImageData(0, 0, width, height);
} catch(e) {
/* security error, img on diff domain */
return false;
}
length = data.data.length;
while ( (i += blockSize * 4) < length ) {
++count;
rgb.r += data.data[i];
rgb.g += data.data[i+1];
rgb.b += data.data[i+2];
}
// ~~ used to floor values
rgb.r = ~~(rgb.r/count);
rgb.g = ~~(rgb.g/count);
rgb.b = ~~(rgb.b/count);
return rgb;
}
The following line is CORS-relevant:
data = context.getImageData(0, 0, width, height);
Although I believe I have set up CORS correctly, I can live with this code failing in some browsers. It seems to work fine in Firefox and IE11, for example. If it fails, I would expect it to fail calculating the dominant color. However, something far worse is happening in highly specific cases: the image is not shown alltogether.
My thinking is that my 'classic' loading of the image via img src tags should have nothing to do with this script working or failing, in all cases at least the image should just load, irrespective of the canvas trick.
Here are the situations I discovered where the image does not load alltogether, which I consider a major issue:
On iOS7 on iPhone 5, the first load works fine. The calculation may fail but the image loads. Refreshing the page often breaks the image. 3rd and 4th tries then continue to succeed, and so on.
Worse, at work in Chrome 36 the image does not load alltogether. I say at work, since at home it is not an issue. Possibly a proxy makes the difference. I can refresh all I want, for images that do not have the calculation ran yet, it keeps failing.
The natural thing to do then is to debug it using Chrome's inspector. Guess what? With the inspector open, it always succeeds. The image will always load and the CORS request headers and responses look perfectly fine. This leaves me with virtually no way to debug this. I can tell though that when opening the inspector when the image does not load does give me the "CORS error" in the console, from the previous request I made. Refreshing with the inspector open will then make that go away.
From reading other questions I've learned that cache may be an influence, yet more likely the issue lies in the origin header not sent by the browser. I believe the issue may be in that direction, yet I fail to understand this:
How it influences my "normal" loading of the image using img tags
How it is only an issue behind a proxy (supposedly) in Chrome, and only when the inspector windows is closed
How it works so unreliably and inconsistently in Safari on iOS
As said, I can live with only some browsers succeeding with the canvas part, but I can't live with the image not being normally loaded in any case. That part should just work.
I realize the situation is incredibly hard for you to debug, but I hope my explanation triggers some much-needed help.
Update: I've discovered that when I remove crossorigin="anonymous" from the img tag, the image will load correctly in the specific scenarios I mentioned. However, the consequence of that move is that the color calculation will no longer work in Chrome, not at home and not at work. It continues to work in Firefox though. I'm investigating what to do next.
I managed to solve the issue myself. I still cannot fully explain cause and effect here, but this is what I did:
I removed crossorigin="anonymous" from the html's img element. This will at least make sure that the image is always loaded.
The color calculation part I solved by basically rewriting its logic:
var imgSrc = $('#<?= $bigimage['image_id'] ?>').attr('src');
var cacheBurstPrefix = imgSrc.indexOf("?") > -1 ? '&' : '?';
imgSrc += cacheBurstPrefix + 'ts=' + new Date().getTime();
var imagePreloader = new Image();
imagePreloader.crossOrigin = "Anonymous";
imagePreloader.src = imgSrc;
$(imagePreloader).imagesLoaded(function() {
var rgb = getAverageRGB(imagePreloader);
document.body.style.backgroundColor = 'rgb('+rgb.r+','+rgb.g+','+rgb.b+')';
if (rgb!==false) {
$.get(basepath + "image/<?= $bigimage['image_id'] ?>/setcolor/" + rgb.r + "-" + rgb.g + "-" + rgb.b);
}
});
Instead of reusing the img element from the html, I'm creating a new in-memory image element. Using a cache bursting technique I'm making sure it is freshly loaded. Next, I'm using imagesLoaded (a 3rd party plugin) to detect the event of this in-memory image being loaded, which is far more reliable than jQuery's load() event.
I've tested extensively and can confirm that in no case does normal image loading ever break again. It works in every browser and proxy situation. As an added bonus, the color calculation part now seems to work in far more browsers, including several mobile browsers.
Although I am still not confident on the root cause, after much frustration I'm very happy with the new situation.

Downloading a dynamically generated SVG file from the browser

If I create an image using HTML SVG element, can I then offer this as an SVG file download to the user. For example I may want to load an SVG image, apply some basic transformations to it, add some text, then let the user download the result as a vector image.
Is that possible? I have been doing something similar with Canvas but have been struggling creating a vector image. I wasn't aware that SVG elements were so versatile when I cam across them this morning but if I can do the above it would be great.
Simple solution using a data URI:
var svg_root = document.getElementById('your_svg_root_element_here');
var svg_source = svg_root.outerHTML;
var svg_data_uri = 'data:image/svg+xml;base64,' + btoa(svg_source);
var link = document.getElementById('anchor_element');
link.setAttribute('href', svg_data_uri);
Although it worked, when clicking on the link, the browser stalled for a few seconds.
This seems to be the simplest solution and should be compatible with all modern browsers. However, it has some noticeable overhead. If someone else knows a different solution (maybe using blobs or something similar), please add here as another answer!

Example of Click Map is not working for me

Sorry by this dummy question! :D
I´m trying to make a clickable map with html5 canvas element, I find this good example: http://www.rubydesigner.com/blog/click-map-using-html5-canvas
But when a download it (CTRL+S) from Chrome it doesnt work. It download the html page and files folder with the JS a images, I checked the path to the images, but still the map doesnt appear. What is the problem?
UPDATE
Initial assumption about CORS turns out to not be the case here.
The code seemed to work in Chrome and although CORS typically is the cause when downloading files and using canvas with local (file://) file references. As localhost is used here via XAMMP this won't be the cause and it turns out there are more than one bugs in the online code.
Specifically the way it calculates the coordinates for the mouse:
var datapos = ((e.offsetY-2) * 300 * 4) + ((e.offsetX-1) * 4);
This will result in a NaN value due to offsetX/Y which of course cannot be used for any index.
The more appropriate way is something like this, here also compensating for canvas offset:
var rect = map_wrapper.getBoundingClientRect();
var datapos = ((e.clientY - (rect.top |0)) * 300 * 4) +
((e.clientX - (rect.left|0)) * 4);
However, I have never came across a floating point position for an element which seem to be case here (rect.top shows a float value in my browser, another little surprise) and therefor I am forcing the value to integer here (normally not necessarily.. I didn't dig deep into this). As debugging the whole code is a bit out of the scope here I will leave it with that and to OP to locate other bugs.
Correcting the position will at least give a usable index for the pixel array which in turn will return a valid (not necessarily correct it turns out, which leave checking of image, tolerane in case gamma/color correction is applied....) value for the red component (still issues when testing but as said, it's a bit out of the scope to do a full debug and correction).
Hopefully this can lead you to where the other errors are. I did not go through the html etc.

Preloading images (in Chrome) [duplicate]

I am pre-loading some images and then using them in a lightbox. The problem I have is that although the images are loading, they aren't being displayed by the browser.
This issue is specific to Chrome. It has persisted through Chrome 8 - 10, and I've been trying on and off to fix it all this time and have got nowhere.
I have read these similar questions,
Chrome not displaying images though assets are being delivered to browser
2 Minor Crossbrowser CSS Issues. Background images not displaying in Google Chrome?
JavaScript preloaded images are getting reloaded
Which all detail similar behaviour but in Chrome for Mac. Whereas this is happening in Windows.
All other browsers seem to be fine.
If you have Firefox and Chrome open, load the page in Firefox, and then in Chrome, the images appear.
Once you have manually loaded the images, using the Webkit webdev toolbar thingy, they always show up
All the links the images and such are fine and working
Clearing everything from Chrome doesn't seem to make any difference (cache, history, etc)
If anyone has any ideas it would be fantastically helpfull, as I'm literally all out of options here.
PS, Apologies if there are late replies, I'm off on holiday for a week tomorrow! :D
Update
Here is the javascript function which is preloading the images.
var preloaded = new Array();
function preload_images() {
for (var i = 0; i < arguments.length; i++){
document.write('<');
document.write('img src=\"'+arguments[i]+'\" style=\"display:none;\">');
};
};
Update
I'm still having issues with this, and I've removed the whole preloading images function. Perhaps delivering a style sheet via document.write() isn't the best way?
Chrome might not be preloading them as it's writing to the DOM with no display, so it might be intelligent enough to realise it doesn't need to be rendered. Try this instead:
var preloaded = new Array();
function preload_images(){
for (var x = 0; x < preload_images.arguments.length; x++)
{
preloaded[x] = new Image();
preloaded[x].src = preload_images.arguments[x];
}
}
The Javascript Image object has a lot of useful functions as well you might find useful:
http://www.javascriptkit.com/jsref/image.shtml
onabort()
Code is executed when user aborts the
downloading of the image.
onerror()
Code is executed when an error occurs
with the loading of the image (ie: not
found). Example(s)
onload()
Code is executed when the image
successfully and completely downloads.
And then you also have the complete property which true/false tells you if the image has fully (pre)loaded.
It turns out that Chrome takes into account the HTTP Caching and discards any preloaded images immediately after preload if the Caching is incorrectly set to expire.
In my case I am generating the images dynamically and by default the response was sent to the browser with immediate expiration.
To fix it I had to set the following below:
Response.Cache.SetExpires(DateTime.Now.AddYears(1));
Response.Cache.SetCacheability(HttpCacheability.Public);
return File(jpegStream, "image/jpeg");