i am getting frames from gif using Libgif.
and then i am appending those frames in the div with Id = frames.
then i am taking those frames and trying to add each frames one after the other in canvas to make a spritesheet.
in the end i am getting an image in canvas but instead of getting different frames i am getting same image in the spritesheet.
Please help me find the issue.
I had taken canvas width 10000 assuming a gif wont have frames more than 100.
c = document.getElementById("myCanvas");
ctx = c.getContext("2d");
ctx.clearRect(0, 0, ctx.width, ctx.height);
ctx.beginPath();
var imageGiF = "";
var total = 0;
let canvasWidth = 0;
let canvasHeight = 0;
$('div.gifimage img').each(function(idx, img_tag) {
var total = 0;
if (/^.+\.gif$/.test($(img_tag).prop("src"))) {
var rub = new SuperGif({
gif: img_tag,
progressbar_height: 0
});
rub.load(function() {
for (let i = 0; i < rub.get_length(); i++) {
total += 1;
rub.move_to(i);
// var canvas = cloneCanvas(rub.get_canvas());
var canvas = rub.get_canvas().toDataURL("image/png");
img = $('<img id = "gifframe' + i + '"src= "' + canvas + '" class= frameimages>');
$("#frames").append(img);
}
var frameimages = document.getElementById("frames").querySelectorAll(".frameimages");
var totalimages = frameimages.length;
x = 0;
y = 0;
for (let i = 0; i < frameimages.length; i++) {
img = document.getElementById("gifframe" + i + "");
img.onload = function() {
ctx.drawImage(img, i * 100, 0, 100, 100);
total++;
console.log(total);
}
}
totalwidth = (total) * 100;
c.width = totalwidth;
c.height = 100;
setTimeout(() => {
imageGiF = c.toDataURL("image/png");
console.log(imageGiF);
// addBgimg(imageGiF)
}, 10);
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/buzzfeed/libgif-js/master/libgif.js"></script>
<div class="gifimage" id="placehere">
<img src="https://media1.giphy.com/media/bzUwzbxcvJ3XQlcnoi/giphy.gif" alt="">
</div>
<div id="frames" class="classGIF"></div>
<canvas id='myCanvas' width="10000" height="300"></canvas>
You were looping through the images, using img in your event handler.
However, this variable img in the outer scope was overridden by every loop, until it was finished looping through everything, then img was stuck on the last frame added.
Then when the event handler triggered, it added the last frame in every instance, because that was the value of img at that point. The loop was done before the images could load.
By adding it to it's own scope by wrapping it in a function, the variable is preserved.
I also modified your code to store the DOM img elements in an array, so you don't need expensive DOM lookups which makes your code a tad bit faster.
I added comments in the code to explain my changes.
c = document.getElementById("myCanvas");
ctx = c.getContext("2d");
ctx.clearRect(0, 0, ctx.width, ctx.height);
ctx.beginPath();
var imageGiF = "";
var total = 0;
let canvasWidth = 0;
let canvasHeight = 0;
$('div.gifimage img').each(function(idx, img_tag) {
var total = 0;
if (/^.+\.gif$/.test($(img_tag).prop("src"))) {
var rub = new SuperGif({
gif: img_tag,
progressbar_height: 0
});
rub.load(function() {
// An array for the image references
let images = [];
// Keep the reference to save on expensive DOM lookups every iteration.
let frames = $("#frames");
for (let i = 0; i < rub.get_length(); i++) {
total += 1;
rub.move_to(i);
// var canvas = cloneCanvas(rub.get_canvas());
var canvas = rub.get_canvas().toDataURL("image/png");
img = $('<img id = "gifframe' + i + '"src= "' + canvas + '" class="frameimages">');
// Use the reference to append the image.
frames.append(img);
// Add image to images array with the current index as the array index.
// Use the jQuery get method to get the actual DOM element.
images[i] = img.get(0);
}
var frameimages = document.getElementById("frames").querySelectorAll(".frameimages");
var totalimages = frameimages.length;
x = 0;
y = 0;
// Loop through all the images in the image array
// Using a scope so the reference to img won't be overridden.
images.forEach((img, index) => {
img.onload = () => {
ctx.drawImage(img, index * 100, 0, 100, 100);
total++;
console.log(total);
}
})
totalwidth = (total) * 100;
c.width = totalwidth;
c.height = 100;
setTimeout(() => {
imageGiF = c.toDataURL("image/png");
console.log(imageGiF);
// addBgimg(imageGiF)
}, 10);
});
}
});
#frames { display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/buzzfeed/libgif-js/master/libgif.js"></script>
<div class="gifimage" id="placehere">
<img src="https://media1.giphy.com/media/bzUwzbxcvJ3XQlcnoi/giphy.gif" alt="">
</div>
<div id="frames" class="classGIF"></div>
<canvas id='myCanvas' width="10000" height="300"></canvas>
Related
I want to split multiple images into tiles(it must be div or similar). (With Javascript or jQuery.)
and Images should be one below the other.
Its my div;
<div class="reading-content">
<div class="page-break no-gaps">
<img id="image-0" src="image.jpg" class="some-class">
</div>
<div class="page-break no-gaps">
<img id="image-1" src="image1.jpg" class="some-class">
</div>
</div>
example jsfiddle; http://jsfiddle.net/0Lxr2tad/
var t = Date.now();
var img = new Image();
var length = 30;
var ylength = 20;
img.onload = function() {
var width = this.width,
height = this.height,
_length = -length,
i, j;
// create a <div/> with all basic characteristics, to be cloned over and over in the loops below.
var $basicDiv = jQuery('<div/>', {
class: 'splitImg',
css: {
'width': Math.floor(width/length),
'height': Math.floor(height/ylength),
'background-image': 'url(' + img.src + ')'
}
});
// Finding a node in the DOM is slow. Do it once and assign the returned jQuery collection.
// Also, #wrapper's width can be set here.
var $wrapper = $('#wrapper').width(width + length * 2);
for (i = 0; i > _length; i--) {
for (j = 0; j > _length; j--) {
$basicDiv.clone().css({'background-position': `${width/length * j}px ${height/ylength * i}px`}).appendTo($wrapper);
}
}
console.log(Date.now() - t);
}
img.src = 'http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg'; // how to do multiple this??
Anyone can help?
I don't use jquery much so I can suggest javascript option like this:
const targetElement = document.querySelector(...) // I choose the div that we are going to append newdivs
I don't know if it exists but I assume there is an array of content you use for src urls or any other data.
let arrayOfInfo = [{},{}] // this is a hypothetical array of objects that we will use
arrayOfInfo.forEach(obj => {
let newDiv = document.createElement("div");
newDiv.classList.add("page-break","no-gaps")
newDiv.innerHTML=`<img id="image-${obj.index}" src=${obj.url} class="some-class">`
targetElement.append(newDiv);
})
so with that approach you automate everything. If you need to reuse, you can make it into a function and run it wherever you need. It is also handy if you need to change some content later on, so you only change the array values and rest goes auto again.
I hope this was what you need.
I tried to do it again after a long time and I was able to do it yesterday, anyone can use it. ( You can remove .splitImg { some style } class for remove spaces. )
JSFiddle Example
let i = 0;
let seenUrls = new Set()
setInterval(() => {
let url = document.querySelectorAll('#someid p img')[i].src;
let image = document.querySelectorAll('#someid p')[i]
let gor = document.querySelectorAll('#someid p')
if (!seenUrls.has(url)) {
seenUrls.add(url)
var t = Date.now();
var img = new Image();
var length = 5;
var ylength = 5;
img.onload = function() {
var width = this.width,
height = this.height,
_length = -length,
i, j;
// create a <div/> with all basic characteristics, to be cloned over and over in the loops below.
var $basicDiv = jQuery('<div/>', {
class: 'splitImg',
css: {
'width': Math.floor(width/length),
'height': Math.floor(height/ylength),
'background-image': 'url(' + img.src + ')'
}
});
// Finding a node in the DOM is slow. Do it once and assign the returned jQuery collection.
// Also, #wrapper's width can be set here.
var $wrapper = image;
image.style.width = width + length * 2 + "px";
for (i = 0; i > _length; i--) {
for (j = 0; j > _length; j--) {
$basicDiv.clone().css({'background-position': `${width/length * j}px ${height/ylength * i}px`}).appendTo($wrapper);
}
}
console.log(Date.now() - t);
}
img.src = url
i = (i + 1) % gor.length;
}
}, 50)
#someid {
max-width: 100%;
}
#someid p {
display:flex;
flex-wrap:wrap;
margin: 0 auto;
}
#someid p img {
display: none!important;
}
.splitImg {
padding: 1px;
background-clip: content-box;
background-repeat: no-repeat;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="someid">
<p>
<img src="http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg" />
</p>
<p>
<img src="https://www.jqueryscript.net/images/Responsive-Touch-Friendly-jQuery-Gallery-Lightbox-Plugin-lightGallery.jpg" />
</p>
</div>
I'm trying to change image position using JavaScript using my code but for some reason it doesn't work. Can someone explain the reason.
var walk, isWaveSpawned = true;
var walkers = [];
function start()
{
walk = document.getElementById("walk");
draw(); //Animation function
}
function draw()
{
if(isWaveSpawned) //Generate a wave of 5 "walkers"
{
isWaveSpawned = false;
for(var i = 0; i < 5; i++
walkers.push(new createWalker());
}
for(var o = 0; o < walkers.length; o++) //Add 1px to x position after each frame
{
walkers[o].x += walkers[o].speed;
walkers[o].image.style.left = walkers[o].x;
walkers[o].image.style.top = walkers[o].y;
}
requestAnimationFrame(draw);
}
function createWalker()
{
this.x = 0;
this.y = 100;
this.speed = 1;
this.image = walk.cloneNode(false); //Possible cause of issue
}
<!DOCTYPE html>
<html>
<body onload="start()">
<img id="walk" src="https://i.imgur.com/ArYIIjU.gif">
</body>
</html>
My GIF image is visible in top left corner but doesn't move.
P.S. Added a HTML/JS snippet but it outputs some errors while in my end these errors are not seen.
First let's modify the way you're cloning the gif - get rid of this line:
this.image = walk.cloneNode(false);
and insert this:
this.image = document.createElement("img");
This will create a fresh empty HTML image element.
Now assign it's .src property the source of your gif:
this.image.src=document.getElementById("walk").src;
and set the CSS position property to absolute:
this.image.style="position:absolute;";
finally add this new image element to the body using:
document.body.appendChild(this.image);
If you hit run you will still not see any movement because there's still a little fix to do!
Find this line:
walkers[o].image.style.left = walkers[o].x;
and change it to this:
walkers[o].image.style.left = walkers[o].x + "px";
var walk, isWaveSpawned = true;
var walkers = [];
function start() {
walk = document.getElementById("walk");
draw(); //Animation function
}
function draw() {
if (isWaveSpawned) //Generate a wave of 5 "walkers"
{
isWaveSpawned = false;
for (var i = 0; i < 5; i++)
walkers.push(new createWalker());
}
for (var o = 0; o < walkers.length; o++) //Add 1px to x position after each frame
{
walkers[o].x += walkers[o].speed;
walkers[o].image.style.left = walkers[o].x + "px";
walkers[o].image.style.top = walkers[o].y + "px";
}
requestAnimationFrame(draw);
}
function createWalker() {
this.x = 0;
this.y = 100;
this.speed = 1;
this.image = document.createElement("img");
this.image.src = document.getElementById("walk").src;
this.image.style = "position:absolute;";
document.body.appendChild(this.image);
}
start();
<body>
<img id="walk" src="https://i.imgur.com/ArYIIjU.gif">
</body>
I am currently working on a Javascript project and I am struggling with exporting the entire SVG image on the canvas. So far I've been only able to export the visible part of the canvas, with out the "hidden" parts.
How do I capture the full canvas content?
Is there a way to do it without messing around with the original canvas size?
I am using D3.js V3
Screenshot of my project
Here's my code:
var svgString;
window.onload = function(){
setTimeout(function() {
exportSVG = document.getElementById("canvas");
document.getElementById("canvas").style.fontFamily= "lato";
document.getElementById("canvas").style.width= exportSVG.getBBox().width * 1;
document.getElementById("canvas").style.height= exportSVG.getBBox().height * 1;
svgString = getSVGString(exportSVG);
console.log(exportSVG.getBBox().width + " / " + exportSVG.getBBox().height);
svgString2Image(svgString, exportSVG.getBBox().width, exportSVG.getBBox().height, 'png', save); // passes Blob and filesize String to the callback
console.log("svg export code loaded");
// console.log(svgString.getBBox().width); document.getElementById("canvas").getBBox().width
}, 5000);
};
function save(dataBlob, filesize) {
saveAs(dataBlob, 'D3 vis exported to PNG.png'); // FileSaver.js function
}
// Below are the functions that handle actual exporting:
// getSVGString ( svgNode ) and svgString2Image( svgString, width, height, format, callback )
function getSVGString(svgNode) {
svgNode.setAttribute('xlink', 'http://www.w3.org/1999/xlink');
var cssStyleText = getCSSStyles(svgNode);
appendCSS(cssStyleText, svgNode);
var serializer = new XMLSerializer();
var svgString = serializer.serializeToString(svgNode);
svgString = svgString.replace(/(\w+)?:?xlink=/g, 'xmlns:xlink='); // Fix root xlink without namespace
svgString = svgString.replace(/NS\d+:href/g, 'xlink:href'); // Safari NS namespace fix
return svgString;
function getCSSStyles(parentElement) {
var selectorTextArr = [];
// Add Parent element Id and Classes to the list
selectorTextArr.push('#' + parentElement.id);
for (var c = 0; c < parentElement.classList.length; c++)
if (!contains('.' + parentElement.classList[c], selectorTextArr))
selectorTextArr.push('.' + parentElement.classList[c]);
// Add Children element Ids and Classes to the list
var nodes = parentElement.getElementsByTagName("*");
for (var i = 0; i < nodes.length; i++) {
var id = nodes[i].id;
if (!contains('#' + id, selectorTextArr))
selectorTextArr.push('#' + id);
var classes = nodes[i].classList;
for (var c = 0; c < classes.length; c++)
if (!contains('.' + classes[c], selectorTextArr))
selectorTextArr.push('.' + classes[c]);
}
// Extract CSS Rules
var extractedCSSText = "";
for (var i = 0; i < document.styleSheets.length; i++) {
var s = document.styleSheets[i];
try {
if (!s.cssRules) continue;
} catch (e) {
if (e.name !== 'SecurityError') throw e; // for Firefox
continue;
}
var cssRules = s.cssRules;
for (var r = 0; r < cssRules.length; r++) {
if (contains(cssRules[r].selectorText, selectorTextArr))
extractedCSSText += cssRules[r].cssText;
}
}
return extractedCSSText;
function contains(str, arr) {
return arr.indexOf(str) === -1 ? false : true;
}
}
function appendCSS(cssText, element) {
var styleElement = document.createElement("style");
styleElement.setAttribute("type", "text/css");
styleElement.innerHTML = cssText;
var refNode = element.hasChildNodes() ? element.children[0] : null;
element.insertBefore(styleElement, refNode);
}
}
function svgString2Image(svgString, width, height, format, callback) {
var format = format ? format : 'png';
var imgsrc = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgString))); // Convert SVG string to data URL
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
var image = new Image();
image.onload = function() {
context.clearRect(0, 0, width, height);
context.drawImage(image, 0, 0, width, height);
canvas.toBlob(function(blob) {
var filesize = Math.round(blob.length / 1024) + ' KB';
if (callback) callback(blob, filesize);
});
};
image.src = imgsrc;
}
Simply change your <svg> viewBox attribute before you serialize it to a string so that it displays everything:
var svg = document.querySelector('svg');
var toExport = svg.cloneNode(true); // avoids having to reset everything afterward
// grab its inner content BoundingBox
var bb = svg.getBBox();
// update its viewBox so it displays all its inner content
toExport.setAttribute('viewBox', bb.x + ' ' + bb.y + ' ' + bb.width + ' ' + bb.height);
toExport.setAttribute('width', bb.width);
toExport.setAttribute('height', bb.height);
var svgAsStr = new XMLSerializer().serializeToString(toExport);
var blob = new Blob([svgAsStr], {type: 'image/svg+xml'});
var img = new Image();
img.onload = drawToCanvas;
img.src = URL.createObjectURL(blob);
function drawToCanvas(evt) {
var canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
canvas.getContext('2d').drawImage(this, 0,0);
document.body.appendChild(canvas);
}
svg{border: 1px solid blue}
canvas{border: 1px solid green}
<svg width="50" height="50" viewBox="0 0 50 50">
<rect x="0" y="0" width="200" height="50" fill="#CCC"/>
</svg>
The problem I have is that when the page is loaded sometimes it displays all the images, sometimes just 2 images and sometimes all. I don´t know why this is happening.
Any ideas?
$('#banners .box img').each(function(index){
var randval = (index+1)*100;
var _this = $(this)
setTimeout(function(){
_this.attr('id' , 'banner' + index);
to_canvas('banner' + index, 300, 223);
}, randval)
});
to_canvas function:
function to_canvas(im,w,h){
var canvas;
var imageBottom;
var im_w = w;
var im_h = h;
var imgData;
var pix;
var pixcount = 0;
var paintrow = 0;
var multiplyColor = [70, 116, 145];
var x_offset = Math.floor(($('#'+im).attr('width') - im_w)/2);
var y_offset = Math.floor(($('#'+im).attr('height') - im_h)/2);
imageBottom = document.getElementById(im);
canvas = document.createElement('canvas');
canvas.width = im_w;
canvas.height = im_h;
imageBottom.parentNode.insertBefore(canvas, imageBottom);
ctx = canvas.getContext('2d');
ctx.drawImage(imageBottom, -x_offset , -y_offset);
imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
pix = imgData.data;
for (var i = 0 ; i < pix.length; i += 4) {
if(pixcount > im_w - (im_h - paintrow) ){
pix[i ] = multiply(multiplyColor[0], pix[i ]);
pix[i+1] = multiply(multiplyColor[1], pix[i+1]);
pix[i+2] = multiply(multiplyColor[2], pix[i+2]);
}
if(pixcount < im_w-1){
pixcount++;
}else{
paintrow++;
pixcount = 0;
}
}
ctx.putImageData(imgData, 0, 0);
$('#'+im).remove();
}
function multiply(topValue, bottomValue){
return topValue * bottomValue / 255;
}
I'm using the canvas function to add a triangle with multiply effect (like Photoshop).
Make sure the images are loaded :
$('#banners .box img').each(function(index, elem){
var randval = (index+1)*100,
self = this,
img = new Image(); // create image object
img.onload = function() { // wait until it's loaded
setTimeout(function(){
self.id = 'banner' + index;
to_canvas('banner' + index, 300, 223);
}, randval)
}
img.src = elem.src; // set source to same as elem
});
Wrap it all in this code to make sure the images are loaded before you execute your script. When you initially load your page, it caches the images(stores them in temp memory), but not before all your elements are rendered. When you reload, it reads the images from the cache–which is much faster than refetching the images again from the server–and therefore the images load about the same time everything else does. This results in visible images.
Like I said, to get your page to work, make sure everything is loaded, then run your script.
$(window).load(function(){
...your scripts(you can exclude functions definitions from this scope)
}
I have been trying to make a script that compares two images in HTML5 and Javascript. But for some odd reason, it always returns that the images are completely the same.
And when looking at what the problem could be, I found out that every data value of every pixel returned, for some odd reason, "0".
So, any idea of what I have done wrong? :)
For some reason I feel like it's something very simple, but I just learned about the canvas element, so yeah.
This is my code:
function compareImg() {
var c1 = document.getElementById("c");
var ctx1 = c1.getContext("2d");
var c2 = document.getElementById("c2");
var ctx2 = c2.getContext("2d");
var match = 0;
var img1 = new Image();
img1.src = "cat.jpg";
img1.onload = function() {
ctx1.drawImage(img1, 0, 0);
}
var img2 = new Image();
img2.src = "bird.jpg";
img2.onload = function() {
ctx2.drawImage(img2, 0, 0);
}
for(var x = 0; x<c1.width; x++) { // For each x value
for(var y = 0; y<c1.height; y++) { // For each y value
var data1 = ctx1.getImageData(x, y, 1, 1);
var data2 = ctx2.getImageData(x, y, 1, 1);
if (data1.data[0] == data2.data[0] && data1.data[1] == data2.data[1] && data1.data[2] == data2.data[2]) {
match++;
}
}
}
var pixels = c1.width*c1.height;
match = match/pixels*100;
document.getElementById("match").innerHTML = match + "%";
}
You are not waiting until your images have loaded and drawn before performing your comparison. Try this:
var img = new Image;
img.onload = function(){
ctx1.drawImage(img,0,0);
var img = new Image;
img.onload = function(){
ctx2.drawImage(img,0,0);
// diff them here
};
img.src = 'cat.jpg';
};
img.src = 'cat.jpg';
As shown above, you should always set your src after your onload.
I suspect that the problem is that your image data is probably not ready at the point you try to use it for the canvas. If you defer that code to the onload handlers, that will (probably) help:
var img1 = new Image(), count = 2;
img1.src = "cat.jpg";
img1.onload = function() {
ctx1.drawImage(img1, 0, 0);
checkReadiness();
}
var img2 = new Image();
img2.src = "bird.jpg";
img2.onload = function() {
ctx2.drawImage(img2, 0, 0);
checkReadiness();
}
function checkReadiness() {
if (--count !== 0) return;
for(var x = 0; x<c1.width; x++) { // For each x value
for(var y = 0; y<c1.height; y++) { // For each y value
var data1 = ctx1.getImageData(x, y, 1, 1);
var data2 = ctx2.getImageData(x, y, 1, 1);
if (data1.data[0] == data2.data[0] && data1.data[1] == data2.data[1] && data1.data[2] == data2.data[2]) {
match++;
}
}
}
var pixels = c1.width*c1.height;
match = match/pixels*100;
document.getElementById("match").innerHTML = match + "%";
}
All I did was add a function wrapper around your code. That function checks the image count variable I added, and only when it's zero (i.e., only after both images have loaded) will it do the work.
(This may be superstition, but I always assign the "onload" handler before I set the "src" attribute. I have this idea that, perhaps only in the past, browsers might fail to run the handler if the image is already in the cache.)
Now another thing: you probably should just get the image data once, and then iterate over the returned data. Calling "getImageData()" for every single pixel is going to be a lot of work for the browser to do.