Is there any simple way to display GIF as image only on webpage. Let say user has posted
http://netdna.webdesignerdepot.com/uploads/2013/04/Dvdp3.gif
which is a gif but when displaying I don't want to show gif. Actually, I am using summernote.
If your browser supports <canvas>
, you can take advantage of it to display frozen gifs:
<canvas id="imageCanvas"></canvas>
Javascript:
var canvas = document.getElementById("imageCanvas"),
image = new Image();
image.src = "/path/to/image.gif";
image.addEventListener("load", function() {
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
canvas.getContext("2d").drawImage(image, 0, 0);
});
Live demo (activate the Javascript panel, and disable the CSS panel).
Tested in IE9-11, Chrome and Firefox.
Update
Using the technique above, there's something more you can do if you actually want an <img>
element and not a <canvas>
:
var preloadImage = new Image(),
finalImage = new Image(),
canvas = document.createElement("canvas");
preloadImage.src = "/path/to/image.gif";
preloadImage.addEventListener("load", function() {
canvas.width = preloadImage.naturalWidth;
canvas.height = preloadImage.naturalHeight;
canvas.getContext("2d").drawImage(image, 0, 0);
finalImage.src = canvas.toDataURL("image/png");
// Append to the DOM. Choose the parent you want.
document.body.appendChild(finalImage);
});
Notice that the canvas isn't even appended to the document, just like preloadImage
.
This works only if:
crossOrigin
enabled (preloadImage.crossOrigin = "anonymous";
).Otherwise the canvas is "tainted" and toDataURL
throws a SecurityError
.