Convert sprite image into CSS animation - javascript

I have an sprite image , I want to animate it , Below is the actual Animation.I coded by just copying code of some other website .It uses some Framework named motio 2.2 , But problem is it is not working in IOS.Below is the sample code and here is demo https://codepen.io/adjmpw/pen/OmxVNO
var blue_cirlce_anim = jQuery('#' + BLUE_CIRCLE_ID);
blue_cirlce_anim.css('cssText', 'display: block !important;');
var motioBC = new Motio(blue_cirlce_anim[0], {
fps: 60,
frames: 97,
vertical: true
});
motioBC.play();
https://codepen.io/adjmpw/pen/OmxVNO
I want to animate following images , Using Css or Javascript or jquery
http://www.humanverify.net/captchalocker/img/blue-circle-anim.png
http://www.humanverify.net/captchalocker/img/blue-circle-loading-anim.png
What I tried So far
var imgHeight = 2844;
var numImgs = 100;
var cont = 0;
var img = $('#container').find('img');
var animation = setInterval( moveSprite,100);
function moveSprite(){
img.css('margin-top', -1 * (cont*imgHeight));
cont++;
if(cont == numImgs){
clearInterval(animation);
}
}
http://jsfiddle.net/aTqGw/406/

Related

JavaScript: set background image with size and no-repeat from random image in folder

I am a javascript newbie...
I'm trying to write a function that grabs a random image from a directory and sets it as the background image of my banner div. I also need to set the size of the image and for it not to repeat. Here's what I've got so far, and it's not quite working.
What am I missing?
$(function() {
// some other scripts here
function bg() {
var imgCount = 3;
// image directory
var dir = 'http://local.statamic.com/_themes/img/';
// random the images
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
// array of images & file name
var images = new Array();
images[1] = '001.png',
images[2] = '002.png',
images[3] = '003.png',
document.getElementById('banner').style.backgroundImage = "url(' + dir + images[randomCount] + ')";
document.getElementById('banner').style.backgroundRepeat = "no-repeat";
document.getElementById('banner').style.backgroundSize = "388px";
}
}); // end doc ready
I messed around with this for a while, and I came up with this solution. Just make sure you have some content in the "banner" element so that it actually shows up, because just a background won't give size to the element.
function bg() {
var imgCount = 3;
var dir = 'http://local.statamic.com/_themes/img/';
// I changed your random generator
var randomCount = (Math.floor(Math.random() * imgCount));
// I changed your array to the literal notation. The literal notation is preferred.
var images = ['001.png', '002.png', '003.png'];
// I changed this section to just define the style attribute the best way I know how.
document.getElementById('banner').setAttribute("style", "background-image: url(" + dir + images[randomCount] + ");background-repeat: no-repeat;background-size: 388px 388px");
}
// Don't forget to run the function instead of just defining it.
bg();
Here's something sort of like what I use, and it works great. First, I rename all my background images "1.jpg" through whatever (ex. "29.jpg" ). Then:
var totalCount = 29;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.getElementById("div1").style.backgroundImage = 'images/'+num+'.jpg';
document.getElementById("div1").style.backgroundSize="100%";
document.getElementById("div1").style.backgroundRepeat="fixed";
}
Then run the function ChangeIt() .

Fancybox and Zoom Effect with Zoom1 Pugin

Working with Fancybox version 1.3.4. Fancybox is working perfectly, I am trying to add the zooom Effect to Fancybox.
Till now i have been able to apply the effect to the image when clicked open in fancybox window. But that is half done, as when i close fancybox, the zoom effect still remains.
I load 5 images and on hover on each image, the top image gets changed. I want to apply the zooom effect on the image which shows when the mouse is moved on the small thumbnail and it shows in big screen. [Here i am unable to apply zooom, i am missing something, but what not sure]
This is my Try Till now:
<div class="CWproductThumbs">
<img class="CWthumb" src="cw4/images/product_thumb_details/012.jpg" alt="Digital HD Video Camera">
<img class="CWthumb" src="cw4/images/product_thumb_details/006.jpg" alt="Digital HD Video Camera">
</div>
Jquery code;
jQuery(document).ready(function(){
// set filename on any image element
var $setSrc = function(triggerEl,targetEl){
var triggerSrc = jQuery(triggerEl).attr('src');
var triggerIndex = triggerSrc.lastIndexOf("/") + 1;
var newFn = triggerSrc.substr(triggerIndex);
var targetSrc = jQuery(targetEl).attr('src');
var targetIndex = targetSrc.lastIndexOf("/") + 1;
var oldFn = targetSrc.substr(targetIndex);
var targetDir = targetSrc.replace(oldFn,'');
var newSrc = targetDir + newFn;
targetEl.attr('src',newSrc);
};
// set href on any link
var $setHref = function(triggerEl,targetEl){
var triggerHref = jQuery(triggerEl).attr('href');
var triggerIndex = triggerHref.lastIndexOf("/") + 1;
var newFn = triggerHref.substr(triggerIndex);
var targetHref = jQuery(targetEl).attr('href');
var targetIndex = targetHref.lastIndexOf("/") + 1;
var oldFn = targetHref.substr(targetIndex);
var targetDir = targetHref.replace(oldFn,'');
var newHref = targetDir + newFn;
targetEl.attr('href',newHref);
};
jQuery('img.CWthumb').hover(function(){
$setSrc(jQuery(this),jQuery('#CWproductImgMain'));
$setHref(jQuery(this).parent('a'),jQuery('#CWproduct105imgLink'));
$setHref(jQuery(this).parent('a'),jQuery('#CWproduct105zoomLink'));
});
jQuery('a.CWimageZoomLink').each(function(){
jQuery(this).fancybox({
'titlePosition': 'over',
'padding': 0,
'margin' : 0,
'overlayShow': true,
'showCloseButton': true,
'hideOnOverlayClick':true,
'hideOnContentClick': true,
'autoDimensions': true,
'centerOnScroll': true,
'showNavArrows':true,
'cyclic':true,
'onComplete' : function() {
jQuery('#fancybox-img').imagezoomsl({innerzoommagnifier: true,
classmagnifier: window.external ? window.navigator.vendor === "Yandex" ? "" : "round-loupe" : "",
magnifierborder: "5px solid #F0F0F0",
zoomrange: [2, 8],
zoomstart: 4,
magnifiersize: [150, 150]})
}
});
jQuery('a.CWtriggerZoomLink').click(function(){
var zoomHref = jQuery(this).attr('href');
jQuery('a.CWimageZoomLink[href="' + zoomHref + '"]').trigger('click');
return false;
});
// fancybox - see http://fancybox.net/api for available options
});
});
Jquery Zooom Plugin used is;
www.zoomsl.tw1.ru

webGL story sphere popups

I am trying to adapt the really cool looking WebGL Story Sphere, source code and css here. There's one big problem: once you click on a news article, the text of the article in the popup is always the same. I want to modify the code so that when you click on an article, the right text appears in the popup.
I'm working from a set of article texts that I specify in the code, e.g. var captions = ["good","better","best"]. Though the article titles and images populate correctly in the popup, I can't get the text to do so. Can you help me?? Here's what I've got:
// function code
var passvar = null; // failed attempt to store texts for later
function initialize() {
math = tdl.math;
fast = tdl.fast;
canvas = document.getElementById("canvas");
g_fpsTimer = new tdl.fps.FPSTimer();
hack();
canvas.addEventListener("mousedown", handleMouseDown, false);
canvas.addEventListener("mousemove", handleMouseMove, false);
canvas.addEventListener("mouseup", handleMouseUp, false);
// Create a canvas 2d for making textures with text.
g_canvas2d = document.createElement('canvas');
window.two2w = window.two2h = g_tilesize;
g_canvas2d.width = two2w;
g_canvas2d.height = two2h;
g_ctx2d = g_canvas2d.getContext("2d");
window.gl = wu.create3DContext(canvas);
if (g_debug) {
gl = wd.makeDebugContext(gl, undefined, LogGLCall);
}
//gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, gl.TRUE);
// Here is where I specify article titles, images, captions
// Titles and images populate the popup correctly, captions don't...
var titles = ["a","b","c"];
var captions = ["good","better","best"];
var images = ['imagesphere/assets/1.jpg',
'imagesphere/assets/bp/2.png',
'imagesphere/assets/bp/3.png'
];
var headlines = titles.concat( titles);
var blurbs = captions.concat( captions);
var tmpImages = [];
var tmpHeadlines = [];
var tmpCaptions = [];
// make a bunch of textures.
for (var ii = 0; ii < g_imagesDownGrid; ++ii) {
var textures = [];
for (var jj = 0; jj < g_imagesAcrossGrid; ++jj) {
var imgTexture = new ImgTexture();
textures.push(imgTexture);
if (tmpImages.length == 0) {
tmpImages = images.slice();
}
if (tmpHeadlines.length == 0) {
tmpHeadlines = headlines.slice();
}
if (tmpCaptions.length == 0) {
tmpCaptions = blurbs.slice();
}
var rando = math.randomInt(tmpImages.length);
var img = tmpImages.splice(rando, 1)[0];
var headline = tmpHeadlines.splice(rando, 1)[0];
var caption = tmpCaptions.splice(rando, 1)[0];
passvar = caption;
if (img.indexOf('videoplay.jpg') > -1){
window.vidtexture = imgTexture;
images = images.slice(1); // dont use that thumb again.
headlines = 'WebGL Brings Video To the Party as Well'
}
imgTexture.load(img, /* "[" + jj + "/" + ii + "]" + */ headline);
}
g_textures.push(textures);
}
// And here's where I try to put this in a popup, finally
// But passvar, the stored article text, never refreshes!!!
<div id="story" class="prettybox" style="display:none">
<img class="close" src="imagesphere/assets/close.png">
<div id="storyinner">
<input id = "mytext">
<script>document.getElementById("mytext").value = passvar;</script>
</div>
</div>
And here is my click handler code:
function sphereClick(e){
window.console && console.log('click!', e, e.timeStamp);
var selected = g_textures[sel.y][sel.x];
window.selected = selected;
animateGL('eyeRadius', glProp('eyeRadius'), 4, 500);
var wwidth = $(window).width(),
wheight = $(window).height(),
story = $('#story').width( ~~(wwidth / 7 * 4) ).height( ~~(wheight / 6 * 5) ),
width = story.width(),
height = story.height(),
miniwidth = 30;
story.detach()
.find('#storyinner').find('h3,img,caption').remove().end().end()
.show();
story.css({
left : e.pageX,
top : e.pageY,
marginLeft : - width / 2,
marginTop : - height / 2
}).appendTo($body); // we remove and put back on the DOM to reset it to the correct position.
$('style.anim.story').remove();
$('<style class="anim story">')
.text( '.storyopen #story { left : ' + (wwidth / 3 * 2) + 'px !important; top : ' + wheight / 2 + 'px !important; }' )
.appendTo($body);
$(selected.img).prependTo('#storyinner').parent();
$('<h3>').text(selected.msg.replace(/\(.*/,'')).prependTo('#storyinner');
$body.addClass('storyopen');
} // eo sphereClick()
There's a lot wrong here, but here's a start. It won't solve your problem, but it will help you avoid issues like this.
var passvar = null; is a global variable.
Your loop for (var ii = 0; ... sets that global variable to a new value on every iteration.
Later, you click something and the global variable passvar is never changed.
If you want to use this pattern, you need to set passvar from your click handler so it has the value that was clicked. Since you didn't actually post your click handlers, it's hard to advise more.
But this is also a bad pattern, functions take arguments for a good reason. Since you have to find your clicked item in the click handler anyway, why not pass it directly which does involve a shared global variable at all?
var handleMouseUp = function(event) {
var story = findClickedThing(event);
if (obj) {
showPopup(story.texture, story.caption);
}
}
Which brings me to this:
var titles = ["a","b","c"];
var captions = ["good","better","best"];
var images = ['imagesphere/assets/1.jpg',
'imagesphere/assets/bp/2.png',
'imagesphere/assets/bp/3.png'
];
When you have 3 arrays, all of the same length, each array describing a different property of an object, you are doing it wrong. What you want, is one array of objects instead.
var stories = [
{
title: "a",
caption: "good",
image: "imagesphere/assets/1.jpg"
}, {
title: "b",
caption: "better",
image: "imagesphere/assets/bp/2.jpg"
}, {
title: "c",
caption: "best",
image: "imagesphere/assets/bp/3.jpg"
},
];
console.log(stories[1].caption); // "better"
Now once you find the clicked object, you can just ask it what it's caption is. And you can pass the whole object to the popup maker. And no field is handled differently or passed around in a different manner, because you are not passing around the fields. You are passsing the entire object.

JQuery Gridster with HTML/Javascript Windows 8 Store App

I decided to create my first windows store app with html/javascript and since you cannot do drag and drop with javascript and listview i have looked for alternatives. Windows store apps support jquery so I found Gridster. It is a jquery plugin to display stuff in a grid with draggable reordering. Each item can be resized as well. I want to use this in my windows store app. Here is a fiddle of the code i inputted into blend, into the html page
var layout;
var grid_size = 100;
var grid_margin = 5;
var block_params = {
max_width: 6,
max_height: 6
};
$(function() {
layout = $('.layouts_grid ul').gridster({
widget_margins: [grid_margin, grid_margin],
widget_base_dimensions: [grid_size, grid_size],
serialize_params: function($w, wgd) {
return {
x: wgd.col,
y: wgd.row,
width: wgd.size_x,
height: wgd.size_y,
id: $($w).attr('data-id'),
name: $($w).find('.block_name').html(),
};
},
min_rows: block_params.max_height
}).data('gridster');
$('.layout_block').resizable({
grid: [grid_size + (grid_margin * 2), grid_size + (grid_margin * 2)],
animate: false,
minWidth: grid_size,
minHeight: grid_size,
containment: '#layouts_grid ul',
autoHide: true,
stop: function(event, ui) {
var resized = $(this);
setTimeout(function() {
resizeBlock(resized);
}, 300);
}
});
$('.ui-resizable-handle').hover(function() {
layout.disable();
}, function() {
layout.enable();
});
function resizeBlock(elmObj) {
var elmObj = $(elmObj);
var w = elmObj.width() - grid_size;
var h = elmObj.height() - grid_size;
for (var grid_w = 1; w > 0; w -= (grid_size + (grid_margin * 2))) {
grid_w++;
}
for (var grid_h = 1; h > 0; h -= (grid_size + (grid_margin * 2))) {
grid_h++;
}
layout.resize_widget(elmObj, grid_w, grid_h);
}
});​
The js references and css can be seen in the source here (where i got the code)
http://jsfiddle.net/maxgalbu/UfyjW/show
I got it working and can drag the boxes around and reorder and resize them...my issue now is how to get it to expand horizontal instead of vertically..the more stuff i put into it, they all go to the bottom. I would like it to expand to the right as new items get added (like the start menu)...it would be perfect if i could turn the grid counter clockwise and keep the items the same orientation..but i know it may not be that easy
i have tried changing some values in the script (in the above code sample) in the html and got some more columns for the boxes to snap to..but eventually they all just revert to snapping to the bottom of one of the first columns...do i have to edit the referenced js files? There's like 4 of them, which one?

Javascript module pattern - what am I doing wrong?

A working version of this is here: http://est.pagodabox.com/client/svedka
I have the following function which I'm trying to convert into a module pattern, but when I try to use one of the function that I return at the bottom, for example:
est_project.closeContent($html);
I get an error that it's not a function. Is there something i'm doing wrong here?
Thanks!
var est_project = (function(){
// Setup functions
var flexDestroy,
cloneCurrent,
clonePosition,
switchSlide,
projectLayout,
contentHeight,
slidePos,
slideClick,
infoToggle,
closeContent;
// Destroy flexslider
flexDestroy = function($slider,$cleanSlider, $projBg) {
// Insert the clone of the un-initialized slide element, and remove the current flexslider
// Effectively "destroys" the current slider
var $curSlide = $slider.find('.flex-active-slide'),
// Get the zero based index of current slide
curSlideIndex = $curSlide.index() - 1,
curBg = $curSlide.find('img').attr('src'),
slideCount = $cleanSlider.data('count'),
i = 0,
$rearrange = $('');
// When you switch projects, the current slide should stay put
if(curSlideIndex !== 0 && slideCount > 1) {
// Cut from the current slide to the end, paste at the beginning
for(i = 0 ; i < slideCount; i += 1) {
if(curSlideIndex > i) {continue;}
$rearrange = $rearrange.add( $cleanSlider.find('li:eq(' + i + ')') );
}
$rearrange.remove();
$cleanSlider.find('li:first-child').before($rearrange)
$cleanSlider.css({'background-image' : 'url(' + curBg + ')'});
}
$slider.after($cleanSlider).remove();
clonePosition(slideheight);
};
return {
// Clone current
cloneCurrent: function($el) {
var $clean,
slideCount = $el.find('li').length;
$clean = $el.clone();
$clean.removeClass('project-current').find('div').removeClass('img-loading');
$clean.data('count',slideCount);
return $clean;
},
// Set the clone position, for when we add it to the DOM or resize the window
clonePosition: function(slideheight) {
var n = $cleanSlider.index(),
$myBg = $cleanSlider.find('div'),
myPosition = n * slideheight;
// Set the position of the inserted clone
$cleanSlider
.css({height: slideheight, top: myPosition, position : 'absolute'});
$myBg
.css({height: slideheight});
},
switchSlide: function($me, $slider) {
$('.project-current').removeClass('project-current');
$me.addClass('project-current');
// Get rid of current flexslider
flexDestroy($slider,$cleanSlider);
// Clone the unitialized slider so we can add it back in later when it gets destroyed
$cleanSlider = cloneCurrent($me);
$me.addClass('flexslider').flexslider({
animation: "slide",
animationSpeed: 500,
slideshow: false,
manualControls: '.dot-nav li a'
});
// After the flexslider initializes, slide the content
setTimeout(function(){
slidePos($me, $slidewrap, slideheight, $win);
},100);
},
// Custom "masonry" function, absolutely positions each project div according to the slide height
projectLayout: function(slideheight,$proj,$projBg) {
var n = 0;
$proj.each(function(){
var $me = $(this),
myPosition = n * slideheight;
// Set all the heights
$me
.css({top: myPosition, position : 'absolute'})
.add($projBg)
.css({height: slideheight});
n++;
});
},
// Set slide wrapper height to window height
contentHeight: function($win, $slidewrap) {
var winHeight = $win.height();
$slidewrap.css({height: winHeight});
},
// Set slide wrapper position to slide to the clicked slide, and set content position
slidePos: function($me, $slidewrap, slideheight, $win) {
var $contentText = $('.project-content .text'),
projNavHeight = Math.round( $win.height() * .1 ),
curIndex = $me.index(),
curTop = 0 - (curIndex * slideheight) + projNavHeight;
$slidewrap.css({transform: 'translate(0,' + curTop.toString() + 'px)'});
$('.corner-btn').add($contentText).css({'padding-top' : projNavHeight});
setTimeout(function(){
$slidewrap.removeClass('tr-none movin').addClass('tr-all');
$('.project').css({opacity: .4})
}, 100);
},
// Click a project, slide to it
slideClick: function($proj) {
$('.project').live('click',function(){
var $me = $(this),
myHref = $me.data('href'),
myTitle = $me.data('title'),
$slider = $('.flexslider'),
indexMy = $me.index(),
indexCur = $('.project-current').index(),
projDir;
$me.css({opacity: 1});
// Stop here if we click on the current project
if($me.hasClass('project-current')) {
return false;
}
History.pushState(null,myTitle,myHref);
});
},
// Hide and show content
infoToggle: function() {
// Open content
$('#corner-btn-info').on('click',function(){
$html.addClass('show-content');
if($('.project-content .text').height() <= $win.height()) {
$html.addClass('no-overflow');
}
$('.project-content-wrap').css({'z-index': 10});
});
// Close content
$('#corner-btn-close').live('click',function(){
closeContent($html);
});
},
closeContent: function($html) {
$html.removeClass('show-content');
setTimeout(function(){
$('.project-content-wrap').css({'z-index': -1});
$html.removeClass('no-overflow');
$('#classy').animate({scrollTop: 0})
},300);
}
};
});
The problem is that you're not executing the anonymous function, your code is the equivalent of:
var est_project = function() {};
You need to execute the function if you want it to return the functions defined in it.
Just replace the last line:
});
By:
}());
Or you can keep your code and call the closeContent function like this:
est_project().closeContent();
But I guess that's not what you want :-) You'd instantiate a new object everytime you call the est_project function.
At the start and end of your file just attach the object to window with the executed function and wrap whole function inside a self executing function. like this
(function(global) {
//your code goes here
global.est_project = est_project();
})(this)

Categories

Resources