Why does drawing an animated gif on canvas only update after reselecting the tab? - google-chrome

I would like to display an animated gif on canvas with some transformations applied. To test things, I'm currently just trying to display the animated gif on the canvas, so that it is essentially equal to displaying the gif as a regular <img> tag.
I'm using Chrome and webkitRequestAnimationFrame. On each request frame, I draw the image. When the gif frame changes, this should be reflected on the canvas. This works only partially:
Just watching the canvas does not make it update. Instead, one, still frame is begin drawn.
Reselecting the tab (i.e. selecting another and selecting the canvas tab again) does update it to a new frame, but after that it freezes again.
This is a fiddle I set up: http://jsfiddle.net/eGjak/93/.
How can I draw an animated gif on canvas with it actually animating?

Answer no longer valid
It looks like the behavior described here (writing an img tag referencing an animated gif to a canvas results in different frames of the gif being written if the img is part of the DOM or visible) has changed at least in Chrome. There may or may not be documentation of what is correct behavior for this. :)
Also, webkitRequestAnimationFrame no longer has the behavior of taking one additional argument, an element X such that when X is not visible, the requested function will not run. For performance and battery life reasons, you may want many of the functions that you pass to requestAnimationFrame to check for visibility before they do anything that will require drawing.
Before:
Check out a fixed version:
http://jsfiddle.net/eGjak/96/
If you add a console.log() to the function that paints the image, you'll see that it is being called. The problem seems to be that the image itself does not animate, probably because the browser does not bother to update an animated image that is not part of the DOM.
My solution was to make the animated gif part of the DOM and size 0 and it works just fine.
You can verify that the animation is being shown on the canvas and not in the image tag by loading up http://jsfiddle.net/eGjak/96/show/ and inspecting the elements with ctrl-shift-I on Windows or Linux / alt-cmd-I.
EDIT: Here's a bonus!
webkitRequestAnimationFrame takes one more argument than the Mozilla equivalent to allow your animation to only run when the element that is being animated is visible. Check out
http://jsfiddle.net/kmKZa/8/
and open up the console. You'll see that when you hide the canvas, the animation function stops being called. When you toggle the canvas visible again, the animation function will be called again.

Related

How do I make my html gif unloop? [duplicate]

I have an animated gif in an img tag that I start by rewriting the src attribute. The gif was created, though, to loop and I only want it to play once. Is there a way, with Javascript or jQuery, to stop an animated gif from playing more than once?
I was having the same problem with an animated gif. The solution is rather simple.
Open the Animated gif in Photoshop.
Go to the Window tab and select timeline(if the timeline is not already open).
At the bottom of the timeline panel, you will find an option, which says "Forever".
Change that to "Once".
Go to File> Export> Export for Web and save it as a gif.
That should do it.
can you find out how long the gif takes to loop once?
if so then you can stop the image like this:
pseudocode:
wait until the end of the image (when it is about to loop)
create a canvas element that has a static version of the gif as currently displayed drawn on it
hide gif
display canvas element in a way that makes it look like the gif froze
javascript:
var c = $("canvas")[0];
var w = c.width;
var h = c.height;
var img = $("img")[0];
setTimeout(function () {
c.getContext('2d').drawImage(img, 0, 0, w, h);
$(img).hide();
$(c).show();
},10000);
jsfiddle
edit:
I forgot to add reference to the original answer that I took this from, sorry
Stopping GIF Animation Programmatically
that one doesn't address the time factor you need for only one loop
Also, it has been mentioned that this approach is problamatic in certain cases (It actually didn't work when I try it in firefox right now...). so here are a few alternatives:
mentioned by Mark: edit the gif itself to avoid looping. this is the best option if you can.
but I've run into cases where it was not an option (like automated generation of images by a third party)
instead of rendering the static image with canvas, keep a static image version and switch to stop looping . this probablyhas most of the problems as the canvas thing
Based on this answer, it's kinda expensive, but it works. Let's say a single loop takes 2 seconds. At a setTimeout after 2 seconds kick in a setInterval, that would reset image source every millisecond:
setTimeout(function() {
setInterval(function() {
$('#img1').attr('src',$('#img1').attr('src'))
},1)
}, 2000)
again, probably just a proof of concept, but here's demo: http://jsfiddle.net/MEaWP/2/
Actually it is possible to make a gif to stop after just one iteration or any specific number of iterations, see an example below (if it is not already stopped), or in jsfiddle.
To do that the gif must be created with number of iterations specified. This could be done using Screen to Gif, it allows to open a gif or a bunch of images and edit it frame by frame.
This solution also allows you to reset the animation by imgElem.src = imgElem.src; but this does not work in MS IE/Edge.
Jurijs Kovzels's answer works in some condition but not in all.
This is browser-dependent.
It works well with Firefox. But In Google Chrome and Safari, it does not work if the gif is on the same server. The example he provided works because the gif is on the external server.
To restart gifs stored on the internal server, using Google Chrome and Safari, you need extra steps to make it work.
const img = document.getElementById("gif");
img.style = "display: none;";
img.style = "display: block;";
setTimeout(() => {
img.src = img.src;
}, 0);
This is inspired by this answer.
Not sure if this is the best way to respond to everyone and have it appear after all the previous answers and comments, but it seems to work.
I don't have much control over the gif. People post whatever gif they want as the "thankyou.gif in their account directory and then the ThankYou code runs whatever they've put there when a comment is submitted to a form they've posted. So some may loop, some may not, some may be short, some may be long. The solution I've come to is to tell people to make them 5 seconds, because that's when I'm going to fade them out, and I don't care if they loop or not.
Thanks for all the ideas.
I know I am pretty late here but..here it is...
I don't know if you would go to this length but let me share a trick.
Open the GIF in Macromedia Flash 8(it has deprecated since then), Export the GIF as Animated GIF. You will have to choose the file location. After that you would receive a dialog box with settings. In that, add the number of times you want the animation to happen. Click OK. Problem solved.

How to view source code of canvas element

I am trying to access the source code inside the canvas tag. Is it possible to get source code inside canvas tag?
You cannot get the source code from canvas element . You need to check the javascript to see what's going on in the canvas . Canvas is similar to board where you can draw anything with javascript .
The canvas element is part of HTML5 and allows for dynamic, scriptable
rendering of 2D shapes and bitmap images. It is a low level,
procedural model that updates a bitmap and does not have a built-in
scene graph
If you use Chrome you're in luck. It has an experimental feature for inspecting Canvas elements. So you can actually profile the canvas element and see step by step each call, and see a shot of the output of that call.
In chrome type chrome://flags/ into the URL and once the page loads, find "Enable Developer Tools experiments". Close out of Chrome and once you load it back up, in the inspector you will find a new option under Profiles for "Capture Canvas Frame". Run that and it will output a list of every call performed.
I learned about this through twitter and the following link, enjoy.
http://www.html5rocks.com/en/tutorials/canvas/inspection/

Highlighting Graph Points clicked on in HTML Canvas

I currently have an html page that produces a line graph inside a canvas element. I have also implemented a feature so that when you click on a point in the graph, a table below the canvas displays the information for that graph point, and clears if you click somewhere that isn't a graph point on the canvas. However, there is currently no indicator for what graph point you have selected.
I would like to make it so that the dot you click on either gets bigger, or highlighted, or something. Unfortunately, I don't think there's any way to do that on the one canvas without needing to redraw the entire graph afterwards. If I drew a bigger dot on top of the original, I would then need to erase it and replace it with the smaller one, as well as redrawing the segment of the line graph that was covered by the larger dot.
I was looking into using a second canvas on top of the first with identical dimensions, using a z-index to control which was on top. However, I don't know how this would affect the click event. If two canvasses are on top of each other, is it possible for the click event to register the lower canvas? Does it only register the higher one? I guess I could just change the click event to be for whichever canvas is on top, but keep all the code for drawing on the canvas the same.
Any advice for how to solve this problem?
Solved a few of my own questions.
Firstly, the click event will only recognize whichever canvas is on top. However, I did like I said, and changed my click event to be for the top canvas, while leaving all instructions on the inside to be for the top canvas. Thank goodness I didn't use the 'this' keyword, or the change would have been much more annoying.
To make the graph points highlight, I first added a second canvas on top of my first one, placing them on top of each other by making their positions "absolute" and giving them a z-index of 0 and 1 respectively. Then, inside the if statement where the original click event recognized that a point had been clicked on, I told the top canvas to draw a larger dot on the same coordinates as the first dot (which I had saved in an array). First, I had it clear the top canvas though, so any other highlighted dots would no longer be highlighted. If the canvas was clicked on somewhere other than a dot, nothing was highlighted.

Possible to load an animated gif without playing the animation?

I wonder if there is a way to prevent a browser from actually animating an animated gif, loaded in a <img> tag.
I just want it to display the first frame of the gif and don't play the animation.
I already fear that this isn't possible and I have to extract the first frame and render it to a canvas.
This is kinda an expensive solution, but if you reset image SRC on a very short setInterval it appears as static e.g:
setInterval(function() {
document.getElementById('img1').src = document.getElementById('img1').src
},1)
Demo: http://jsfiddle.net/MEaWP/6/
Maybe this is too simple an answer for you but you could just open the animated GIF in a image editing program of your choice, i.e. Adobe Photoshop or any other free one, and then just save out the GIF without the animation.
Then re-upload the new GIF (without the animation) to wherever you are serving your images from.
If you do use Photoshop you can simply open the file.GIF and go to Window>Animation in the Menu. This will display all the frames in the animated GIF in a new dialog box.
Just delete all the frames and Save As. Just don't overwrite the original with the animation if you will still need that later.

Internet Explorer CPU usage goes high after an animated GIF image has been displayed

I have been working on a web application for some time now and did notice that the CPU usage was a bit high a long time ago, but the development has been halted for a while.
Recently I started developing again and discovered that the CPU usage goes high after an animated GIF image has been display as the background image.
I use Ajax to update content and apply CSS classes to elements to display a loading indicator. I remove the CSS class when the content has finished loading. If I comment out the classes in the stylesheet that contains the GIFs, everything looks normal.
I have tested it in Internet Explorer 7 and Internet Explorer 8.
What can be done to alliviate this problem?
var blabla = function() {
var element = $('id of element');
element.addClassName('a css classname');
new Ajax.Request({some parameters},
onSuccess: function() {
element.removeClassName('a CSS classname');
....
},
onFailure: function() {
element.removeClassName('a CSS classname');
....
},
onComplete: function() {
element.removeClassName('a CSS classname');
....
}
}
}
It's possible that this issue is related to how Internet Explorer loads data needed from CSS classes. Might I suggest an alternate approach: instead of using the loading animation contained within a CSS class, just put the .gif in a visible <img> tag straight into the HTML. Then, when onSuccess or another method is called, you can just run:
$("#ajax-gif").hide();
As already commented on, it looks like it doesn't have anything to do with the GIF image itself, especially not one at 20x20 pixels.
If you are changing the background of a page with a GIF image, it must redraw what's on top of it to a certain extent.
To bring down the CPU usage, either reduce what's on your page before you change the background or stop using GIF images, it's 2011!
If this problem is only occurring in Internet Explorer, it is indeed the redraw issue that commenters to Barnzy's answer have talked about. It should create similar problems across other browsers as well.
One solution would be to use the JavaScript onload event handler to preload all of your GIF images in the DOM, which would reduce the need to redraw and should stop escalating the CPU cycles.
I agree that in 2011 using GIF images is probably not the best approach for web design.