Image Preloading for animation - javascript

I have a banner at the top of some of my webpages. The banner is static until the user clicks on the play button which kick starts the animation.
The animation is one long horizontal image that just rolls around and iv got it overlapping perfectly.
But what I want to happen is to have a smaller alternative image to load first, while the large image loads behind then once it is loaded to replace the original small image so there is no delay on the page...
How do I go about this?
This is my js to get the banner to play on click.
$(document).ready(function()
{
var mwbannerfull = $( '#mwbannerfull' );
var playing = false;
var playarrow = $( '.playarrow' );
var speed = 0.145;
var totalDistance = 4350;
playarrow.click(function()
{
if (playing)
pause();
else
play();
playing = !playing
playarrow.toggleClass('playing');
});
function play()
{
var distance = parseInt(mwbannerfull.css('left'), 10) * -1;
if (isNaN(distance)) distance = 0;
distance = totalDistance - distance;
var time = distance / speed;
mwbannerfull.animate({left: '-' + totalDistance + 'px'}, time, 'linear', function()
{
$(this).css(
{
left: 0
});
play();
});
}
function pause()
{
mwbannerfull.stop();
}
});
HTML:
<div id="mwprobanner">
<a href="#!" class="playarrow">
<i class="icon-play"></i>
<i class="icon-pause"></i>
</a>
<div id="mwbannerfull"></div>
</div>

data-l will store your large image
<img data-l='https://www.google.com.hk/images/srpr/logo11w.png' src='http://www.microsoft.com/global/learning/en-us/PublishingImages/ms-logo-site-share.png' />
 
function startLoading() {
$("img").each(function () {
var _this = $(this);
var src = $(this).attr('data-l');
if (src != "") {
var tmp = $(new Image());
//When loaded
tmp.one('load', function () {
_this.replaceWith(tmp);
});
tmp.attr('src', src);
}
});
}
Image will start loading after 2 seconds.
setTimeout(function(){
startLoading();
},2000);
http://jsfiddle.net/netorz04/

Related

HTML CANVAS - Preload Issue or OnLoad issue - Why do I have to click twice?

I have an HTML page with 2 canvases side-by-side. The left one has a clickable upper region. The right one is where all the drawing takes place. I want the user to click the region on the left, which will load a new image on the right, and replace the one that is already there, but I have to click twice for the new image to show up. Why is this? See code.
THE HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
#centerAll {
margin-left:auto;
margin-right:auto;
width:1300px;
}
</style>
</head>
<body>
<div id="centerAll">
<canvas id="TheLeftCanvas" width="300" height="500"
style="border:2px solid #999999;"></canvas>
<canvas id="TheRightCanvas" width="900" height="500"
style="border:2px solid #999999;"></canvas>
<script type="text/javascript" src="whyClickTwiceForImage.js">
</script>
</div>
</body>
</html>
AND THE JAVASCRIPT
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded () {
canvasApp();
}
function canvasApp() {
var rightCanvas = document.getElementById("TheRightCanvas");
//THE EMPTY CANVAS ON THE RIGHT, WHICH DRAWS THINGS
var rightCtx = rightCanvas.getContext("2d");
var leftCanvas = document.getElementById("TheLeftCanvas");
//THE EMPTY CANVAS ON THE LEFT, WHICH HANDLES USER CLICKS
var leftCtx = leftCanvas.getContext("2d");
var currentMouseXcoor = 0;
var currentMouseYcoor = 0;
var imagesToLoad = 0; //USED TO PRE-LOAD SOME OTHER VISUALS, BEFORE THE USER STARTS
var imagesLoaded = 0;
var picturesTheUserCanChoose = ["pic01.png", "pic02.png",
"pic03.png", "pic04.png", "pic05.png"];
var nameOfPicTheUserChose = "pic05.png"; //LET'S JUST SAY "pic05.png" IS A PLACEHOLDER PICTURE... TO START OFF
var legitMouseClick = 0; //DID THE USER CLICK IN THE UPPER REGION OF THE LEFT CANVAS?
var loaded = function(){ // "LOADED" AND "LOAD IMAGE" ARE USED TO PRELOAD ALL THOSE OTHER VISUALS BEFORE THE USER STARTS
imagesLoaded += 1;
if(imagesLoaded === imagesToLoad){
imagesToLoad = 0;
imagesLoaded = 0;
drawScreen(); // OK... ALL LOADED.... SO DRAW THE SCREEN
}
}
var loadImage = function(url){ // "LOADED" AND "LOAD IMAGE" ARE USED TO PRELOAD ALL THOSE OTHER PICS BEFORE THE USER STARTS
var image = new Image();
image.addEventListener("load",loaded);
imagesToLoad += 1; // ADD THE NUMBER TO THE IMAGES NEEDED TO BE LOADED
image.src = url;
return image; // ...AND RETURN THE IMAGE
}
//--------------------------------------------------------------
leftCanvas.addEventListener('mouseup', function(evt) { var
mousePos = doMouseUp(leftCanvas, evt);
currentMouseXcoor = mousePos.x; currentMouseYcoor =
mousePos.y; processMousePosition();}, false);
//--------------------------------------------------------------
function drawScreen(){
clearScreen();
rightCtx.drawImage(picture1,0,0,100,100);
}
//THIS FUNCTION PRESUMABLY LOADS IMAGES ON-THE-FLY... BUT WHY DOES THE LEFT CANVAS REGION HAVE TO BE CLICKED TWICE FOR THE NEW IMAGE TO SHOW?
function processMousePosition() {
if(currentMouseYcoor >= 0 && currentMouseYcoor <= 50){
//IF THE CLICK IS IN THE UPPER REGION OF THE LEFT CANVAS
nameOfPicTheUserChose = picturesTheUserCanChoose[0];
//WE'LL SAY THE USER CHOSE THE VERY FIRST PIC IN THE ARRAY
picture1.src = ("picturesFolder/"+ nameOfPicTheUserChose);
picture1.onload = legitMouseClick = 1;//I JUST MADE UP FOR SOMETHING TO HAPPEN WHEN THE NEW PICTURE LOADS???
alert(nameOfPicTheUserChose); // THE ALERT CORRECTLY SHOWS THE NAME OF THE FIRST PIC IN THE ARRAY
}
drawScreen();
}
function doMouseUp(leftCanvas, evt){
var rect = leftCanvas.getBoundingClientRect();
return { x: evt.clientX - rect.left, y: evt.clientY - rect.top};
}
function clearScreen(){
rightCtx.clearRect(0, 0, 900, 500);
leftCtx.clearRect(0, 0, 300, 500);
}
//var someOtherVisual1 =
//loadImage("backgroundArtFolder/someOtherVisual1.jpg");
//var someOtherVisual2 =
//loadImage("backgroundArtFolder/someOtherVisual2.png");
//var someOtherVisual3 =
//loadImage("backgroundArtFolder/someOtherVisual3.png");
//var someOtherVisual4 =
//loadImage("backgroundArtFolder/someOtherVisual4.png");
//var someOtherVisual5 =
//loadImage("backgroundArtFolder/someOtherVisual5.png");
var picture1 = loadImage("picturesFolder/pic05.png");
//LET'S JUST PRELOAD "pic05.png" AS A PLACEHOLDER... TO START OFF
}
You can change the image load on click in js file picture1.src = ("picturesFolder/"+ nameOfPicTheUserChose); to picture1 = loadImage("picturesFolder/"+nameOfPicTheUserChose); and picture1.onload = legitMouseClick = 1; to 'legitMouseClick = 1'

Smooth progress bar from video file

I have a homepage video, and a div to display the progress. The problem tho, is that the progress bar increases in little chunks, I would like it to be smooth, I was thinking of adding an animate() to the process. Do you have a better idea?
var homepageVideo = $('#homepage_video').get(0);
var progressBar = $('.homepage_progress_bar--progress-bar');
var progressBarContainerWidth = $('.homepage_progress_bar--progress-bar-default').width();
var progress = 0;
var homepageVideoDurationCurrentTime = 0;
var homepageVideoDuration = 0;
homepageVideo.play();
homepageVideo.ontimeupdate = function() {
updateProgressBar()
};
function updateProgressBar() {
homepageVideoDurationCurrentTime = homepageVideo.currentTime;
homepageVideoDuration = homepageVideo.duration;
progress = getProgress(homepageVideoDurationCurrentTime, homepageVideoDuration);
progressBar.width(progressBarContainerWidth * progress);
}
function getProgress(currentTime, duration) {
return (100 - (((duration - currentTime) * 100)/duration))/100;
}
My HTML is simply
<div class="homepage_progress_bar--progress-bar-default">
<div class="homepage_progress_bar--progress-bar"></div>
</div>
Working Fiddle

Trouble changing images with a timer with javascript

I am writing a website and I want to animate through various images on a timer. I have an array listing each of the images (as a number which is used to build the filename). The animation should go through those numbers and in turn change the image. This code is not working and any help would be appreciated.
<img id="myImg" src=" http://old.ycombinator.com/images/yc500.gif" width ='100' height='100'/>
<script>
var myImages = [1, 2, 3, 5]
var img_index = 0;
var timer;
var imgId = "myImg";
// Bind the image onload event like this:
document.getElementById(imgId).onload = animate();
// Start animation
function animate() {
me = document.getElementById(imgId);
me.src = "coolimg." + myImages[img_index] + ".jpg"
img_index++;
if (img_index == myImages.length){
img_index = 0;
}
timer = setTimeout(animate, 1000);
}
</script>

I want to repeat a process in jquery

I have this function
var flakeImage = new Image();
function loadImage(){
flakeImage.onload = drawFlake;
flakeImage.src = "game/snowflake.png";
}
and this one that initialises the image
function initFlake() {
flakex = Math.random()*(WIDTH-140)+70;
flakey = (Math.random()*20)+70;
flakes = Math.random()*40;
}
and this one that updates the image so it will look like it s actually falling
function updateFlake(){
flakey = flakey + 1;
}
and also the draw function
function drawFlake() {
context.drawImage(flakeImage, flakex, flakey, flakes, flakes);
}
I want to make it look like it s snowing in my canvas. I can't use a for loop because it will just modify the same picture . I tried making a big array with the same picture, but in the end I don't get that effect .. because the images have to keep falling randomly . How should I combine an array with that image stored at random positions with an interval to get that effect ?
You can use setInterval().
doSomething: function() {
clearInterval(myInterval);
myInterval = setInterval(function() {
// update flake position
updateFlake();
}, timeInMilliseconds);
},
This runs the function given as a parameter every timeInMilliseconds milliseconds. The setInterval() function returns an ID which you can pass to clearInterval() in order to stop updating.
You can also pass a function directly.
doSomething: function() {
clearInterval(myInterval);
myInterval = setInterval(updateFlake, timeInMilliseconds);
},
EDIT: OP, you can do this just fine without relying on HTML5 canvas, instead use DOM elements:
JS BIN
Javascript:
function update () {
var myInterval = null;
clearInterval(myInterval);
myInterval = setInterval(function() {
// update flake position
$("#holder > img").each(function() {
if ($(this).position().top >= $(window).height())
$(this).remove();
else
$(this).css({top: $(this).position().top+=3});
});
}, 50); //update each of the drawn children
}
function drawFlake() {
clearInterval(myInterval);
var myInterval = null;
myInterval = setInterval(function() {
var randX = (Math.floor((Math.random() * $(window).width()) + 1));
var $img = $('<img>');
$img.attr('src','flake.png');
$("#holder").append($img);
$img.css({left: randX, top: 0, position:'absolute'});
}, 2000); //draw a new flake every 2 seconds
update();
}
HTML:
<body onload="drawFlake()">
<div id="holder"></div>
</body>
CSS:
body {
background: white;
}
#holder {
position: relative;
width: 100%;
height: 100%;
}

onClick event on image while already moving

I'm trying to make an image that moves to the right on my website. When you click the image, it should move to the left. For now, this doesn't happen, any ideas? If possible, in pure Javascript and no Jquery ;)
Also, if you click the image for a second time, it should move to the right again. Every consecutive time, the image should move to the other side. I guess this would be best with a for-loop?
<script type"text/javascript">
window.onload = init;
var winWidth = window.innerWidth - movingblockobject.scrollWidth; //get width of window
var movingblock = null //object
movingblock.onclick = moveBlockLeft();
function init() {
movingblock = document.getElementById('movingblockobject'); //get object
movingblock.style.left = '0px'; //initial position
moveBlockRight(); //start animiation
}
function moveBlockRight() {
if (parseInt(movingblock.style.left) < winWidth) { // stop function if element touches max window width
movingblock.style.left = parseInt(movingblock.style.left) + 10 + 'px'; //move right by 10px
setTimeout(moveBlockRight,20); //call moveBlockRight in 20 msec
} else {
return;
}
}
function moveBlockLeft () {
movingblock.style.right = parseInt(movingblock.style.right) + 10 + 'px'
}
</script>
Please first go through the Basics of javascript before trying out something .
window.onload = init;
var winWidth = window.innerWidth;
var movingblock = null;
var intervalid = null;
var isLeft = false;
function init() {
console.log('Init');
movingblock = document.getElementById('movingblockobject');
movingblock.style.left = '0px';
intervalid = setInterval(function() {
moveBlock(true);
}, 2000);
movingblock.onclick = function() {
moveBlock(false);
};
}
function moveBlock(isSetInterval) {
if (!isSetInterval)
isLeft = !isLeft;
if (parseInt(movingblock.style.left) < winWidth) {
if (isLeft)
movingblock.style.left = parseInt(movingblock.style.left) - 10 + 'px';
else
movingblock.style.left = parseInt(movingblock.style.left) + 10 + 'px';
} else {
movingblock.style.left = '0px';
}
}
function moveBlockLeft() {
clearInterval(intervalid);
movingblock.style.right = parseInt(movingblock.style.right) + 10 + 'px';
intervalid = setInterval(moveBlockRight, 20);
}
<div id="movingblockobject" style="width:50px;height:50px;border:solid;position: absolute;">
var movingblock = null
this are mistakes you have delclared it as null and next line you are binding click event.Also for assigning click event you should assign the name of the function.
movingblock.onclick = moveBlockLeft;
above is basic bug there are lot like the above.I feel Self learning is much better for basics
try yourself.
try the above it will work but please try yourself
You should CSS3 transition, works like a charm. Just toggle a class "right"
HTML:
<html>
<head>
<style>
#movingblockobject{
width: 40px;
padding: 10px;
position: fixed;
height:10px;
left:0px;
-webkit-transition: left 2s; /* For Safari 3.1 to 6.0 */
transition: left 2s;
}
#movingblockobject.right{
left:200px;
}
</style>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$( document ).ready(function() {
$('#movingblockobject').on('click', function (e) {
$('#movingblockobject').toggleClass("right");
});
});
</script>
</head>
<body>
<div id="movingblockobject" class="demo">add image here</div>
</body>
</html>

Categories