Continuous Image Vertical Scroller - javascript

I need to adjust the script from http://javascript.about.com/library/blcvert.htm to change direction of scrolling to DOWN.
Could anybody help?
Of course, it would be also helpful if anybody knows/have some other script which produces the same effect.
Thanx
P.S. the script (in readable format is):
var imgAry1 = ['img1.png','img2.png'];
function startCloud() {
new mq('clouds', imgAry1, 380);
mqRotate(mqr);
}
$(document).ready(function() {
startCloud();
});
var mqr = [];
function mq(id, ary, heit) {
this.mqo=document.getElementById(id);
var wid = this.mqo.style.width;
this.mqo.onmouseout=function() { mqRotate(mqr); };
this.mqo.onmouseover=function() { clearTimeout(mqr[0].TO); };
this.mqo.ary=[];
var maxw = ary.length;
for (var i=0;i<maxw;i++) {
this.mqo.ary[i]=document.createElement('img');
this.mqo.ary[i].src=ary[i];
this.mqo.ary[i].style.position = 'absolute';
this.mqo.ary[i].style.top = (heit*i)+'px';
this.mqo.ary[i].style.height = heit+'px';
this.mqo.ary[i].style.width = wid;
this.mqo.appendChild(this.mqo.ary[i]);
}
mqr.push(this.mqo);
}
function mqRotate(mqr) {
if (!mqr) return;
for (var j=mqr.length - 1; j > -1; j--) {
maxa = mqr[j].ary.length;
for (var i=0;i<maxa;i++) {
var x = mqr[j].ary[i].style;
x.top=(parseInt(x.top,10)-1)+'px';
}
var y = mqr[j].ary[0].style;
if (parseInt(y.top,10)+parseInt(y.height,10)<0) {
var z = mqr[j].ary.shift();
z.style.top = (parseInt(z.style.top) + parseInt(z.style.height)*maxa) + 'px';
mqr[j].ary.push(z);
}
}
mqr[0].TO=setTimeout('mqRotate(mqr)',10);
}

On this line:
x.top=(parseInt(x.top,10)-1)+'px';
it says that you take x.top in pixels, parse out the number, subtract one and add the 'px' again. The element's position from top is decreased by 1 each time, so it goes up. All you need to do for it to go down is to add the one.
x.top=(parseInt(x.top,10)+1)+'px';
I also tested this hypothesis on the page you linked :)

Related

Javascript full screen display issues

I have been trying to put a text particle effect on my website. I have tested it on Codepen and works great but does not work on my website.
The text shows but the effect does not work as required. The text stays in a static position on the screen but the hover effect is below the word.
taking the mose through the text does nothing, if I move the mouse to the bottom of the screen the effect works on the text above.
The text stays static, however, when I move scroll down, the position of the text effect stays at the bottom of the screen until it ends up below the div and stops working all together.
I was wondering if someone could help me centre this behind the text.
Also I am keen to change the colour of the text, to a linear gradient from #125eaa to #d52027
The link to the page on my site - https://www.supplementgenie.co.uk/testpage
link to my codepen - https://codepen.io/Paulmcf87/pen/gjpgOB
However, when I run this code on JS Fiddle it gives me a 404 error?
You will see, running code below it works great as on Codepen. It doesnt seem to translate properly to a full screen
Any help would be great
The code I am using
var pixels=new Array();
var canv=$('canv');
var ctx=canv.getContext('2d');
var wordCanv=$('wordCanv');
var wordCtx=wordCanv.getContext('2d');
var mx=-1;
var my=-1;
var words="";
var txt=new Array();
var cw=0;
var ch=0;
var resolution=1;
var n=0;
var timerRunning=false;
var resHalfFloor=0;
var resHalfCeil=0;
function canv_mousemove(evt)
{
mx=evt.clientX-canv.offsetLeft;
my=evt.clientY-canv.offsetTop;
}
function Pixel(homeX,homeY)
{
this.homeX=homeX;
this.homeY=homeY;
this.x=Math.random()*cw;
this.y=Math.random()*ch;
//tmp
this.xVelocity=Math.random()*10-5;
this.yVelocity=Math.random()*10-5;
}
Pixel.prototype.move=function()
{
var homeDX=this.homeX-this.x;
var homeDY=this.homeY-this.y;
var homeDistance=Math.sqrt(Math.pow(homeDX,2) + Math.pow(homeDY,2));
var homeForce=homeDistance*0.01;
var homeAngle=Math.atan2(homeDY,homeDX);
var cursorForce=0;
var cursorAngle=0;
if(mx >= 0)
{
var cursorDX=this.x-mx;
var cursorDY=this.y-my;
var cursorDistanceSquared=Math.pow(cursorDX,2) + Math.pow(cursorDY,2);
cursorForce=Math.min(10000/cursorDistanceSquared,10000);
cursorAngle=Math.atan2(cursorDY,cursorDX);
}
else
{
cursorForce=0;
cursorAngle=0;
}
this.xVelocity+=homeForce*Math.cos(homeAngle) + cursorForce*Math.cos(cursorAngle);
this.yVelocity+=homeForce*Math.sin(homeAngle) + cursorForce*Math.sin(cursorAngle);
this.xVelocity*=0.92;
this.yVelocity*=0.92;
this.x+=this.xVelocity;
this.y+=this.yVelocity;
}
function $(id)
{
return document.getElementById(id);
}
function timer()
{
if(!timerRunning)
{
timerRunning=true;
setTimeout(timer,33);
for(var i=0;i<pixels.length;i++)
{
pixels[i].move();
}
drawPixels();
wordsTxt.focus();
n++;
if(n%10==0 && (cw!=document.body.clientWidth || ch!=document.body.clientHeight)) body_resize();
timerRunning=false;
}
else
{
setTimeout(timer,10);
}
}
function getRandomColor(min, max) {
return Math.random() * (max - min) + min;
}
function drawPixels()
{
var imageData=ctx.createImageData(cw,ch);
var actualData=imageData.data;
var index;
var goodX;
var goodY;
var realX;
var realY;
for(var i=0;i<pixels.length;i++)
{
goodX=Math.floor(pixels[i].x);
goodY=Math.floor(pixels[i].y);
for(realX=goodX-resHalfFloor; realX<=goodX+resHalfCeil && realX>=0 && realX<cw;realX++)
{
for(realY=goodY-resHalfFloor; realY<=goodY+resHalfCeil && realY>=0 && realY<ch;realY++)
{
index=(realY*imageData.width + realX)*4;
actualData[index+3]=realX;
actualData[index+2]=realX;
actualData[index+1]=realY;
}
}
}
imageData.data=actualData;
ctx.putImageData(imageData,0,0);
}
function readWords()
{
words=$('wordsTxt').value;
txt=words.split('\n');
}
function init()
{
readWords();
var fontSize=200;
var wordWidth=0;
do
{
wordWidth=0;
fontSize-=5;
wordCtx.font=fontSize+"px Avenir, sans-serif";
for(var i=0;i<txt.length;i++)
{
var w=wordCtx.measureText(txt[i]).width;
if(w>wordWidth) wordWidth=w;
}
} while(wordWidth>cw-50 || fontSize*txt.length > ch-50)
wordCtx.clearRect(0,0,cw,ch);
wordCtx.textAlign="center";
wordCtx.textBaseline="middle";
for(var i=0;i<txt.length;i++)
{
wordCtx.fillText(txt[i],cw/2,ch/2 - fontSize*(txt.length/2-(i+0.5)));
}
var index=0;
var imageData=wordCtx.getImageData(0,0,cw,ch);
for(var x=0;x<imageData.width;x+=resolution) //var i=0;i<imageData.data.length;i+=4)
{
for(var y=0;y<imageData.height;y+=resolution)
{
i=(y*imageData.width + x)*4;
if(imageData.data[i+3]>128)
{
if(index >= pixels.length)
{
pixels[index]=new Pixel(x,y);
}
else
{
pixels[index].homeX=x;
pixels[index].homeY=y;
}
index++;
}
}
}
pixels.splice(index,pixels.length-index);
}
function body_resize()
{
cw=document.body.clientWidth;
ch=document.body.clientHeight;
canv.width=cw;
canv.height=ch;
wordCanv.width=cw;
wordCanv.height=ch;
init();
}
wordsTxt.focus();
wordsTxt.value="Supplement Genie";
resolution=1;
resHalfFloor=Math.floor(resolution/2);
resHalfCeil=Math.ceil(resolution/2);
body_resize();
timer();
#wordsTxt{
display:none
}
div.pixeltext canvas{
width:98vw;
height:100vh;
}
div.pixeltext{
background-color: #d52027;
<div class="pixeltext">
<canvas id="canv" onmousemove="canv_mousemove(event);" onmouseout="mx=-1;my=-1;">
you need a canvas-enabled browser, such as Google Chrome
</canvas>
<canvas id="wordCanv" width="500px" height="500px" style="border:1px solid black;display:none;">
</canvas>
<textarea id="wordsTxt" style="position:absolute;left:-100;top:-100;" onblur="init();" onkeyup="init();" onclick="init();"></textarea>
<div>
You should define the cw,ch variables based on the canvas dimensions and not on the document.body.clientWidth etc.
Also you should avoid using canv.offsetLeft and canv.offsetTop since your element is inside other positioned elements and the offset properties return the position relative to the closest positioned ancestor.
Using canv.getBoundingClientRect which returns the width/height and top/left/right/bottom properties relative to the viewport will solve the problem.
(your codepen was also using wrong names of the methods you had created)
See https://codepen.io/gpetrioli/pen/rreagp which basically modifies the following methods
function canvMousemove(evt) {
var rect = canv.getBoundingClientRect();
mx = evt.clientX - rect.left;
my = evt.clientY - rect.top;
}
function body_resize() {
var rect = canv.getBoundingClientRect()
cw = rect.width;
ch = rect.height;
console.log(ch);
canv.width = cw;
canv.height = ch;
wordCanv.width = cw;
wordCanv.height = ch;
init();
}
In your site i noticed a timer method which should also be modified to
function timer() {
var rect;
if (!timerRunning) {
timerRunning = true;
setTimeout(timer, 33);
for (var i = 0; i < pixels.length; i++) {
pixels[i].move();
}
drawPixels();
wordsTxt.focus();
n++;
rect = canv.getBoundingClientRect();
if (n % 10 == 0 && (cw != rect.width || ch != rect.height)) body_resize();
timerRunning = false;
} else {
setTimeout(timer, 10);
}
}

error with arrays in javascript

To fully understand this note this; `when the page loads it gets the area of the image (width * height) and creates all the x,y positions for all the positions in the area.
This works fine.
When I have another area from pos x,y and with also an area (width * height) should pop the positions from the first list so it can separate the two areas.
Little bug I noticed is I get little lines that are horizontal to the selected area and they don't extend far from that. I believe the reason is instead of making a clean square inside the image every line is offseted by a pixel or two.
Here's a video of the behaviour https://youtu.be/v1b6dEmfxQw
so since there's already an all positions list this code created a clone of the array and removes the positions.
var drop_boxes = $('.drop-box');
var area_grid = [];
var image_width = $('.img-class')[0].naturalWidth;
var image_height = $('.img-class')[0].naturalHeight;
drop_boxes.each(function() {
var position = $(this).position();
var width = $(this).width();
var height = $(this).height();
var positions_clone = positions.slice(0);
//console.log(positions_clone.length);
var top_offset = parseInt((position['top'] * image_width)/img_width);
var left_offset = parseInt((position['left'] * image_height)/img_height);
position['top'] = top_offset;
position['left'] = left_offset;
var width_offset = parseInt((width * image_width)/img_width);
var height_offset = parseInt((height * image_height)/img_height);
var width_counter = 0;
var height_counter = 0;
var area = width_offset * height_offset;
console.log(position);
console.log(width_offset);
console.log(height_offset);
if (position['top'] < image_height-1 && position['left'] < image_width) {
for (counter = 0; counter < area; counter++) {
var pos = [parseInt(position['left']+width_counter), parseInt(position['top']+height_counter)];
var index = positions.findIndex(function(item) {
// return result of comparing `data` with `item`
// This simple implementation assumes that all `item`s will be Arrays.
return pos.length === item.length && item.every(function(n, i) { return n === pos[i] });
});
//console.log(pos);
if (index > -1) {
positions_clone.splice(index, 1);
}
//area_grid.push(pos);
if (width_counter == width_offset) {
width_counter = 0;
height_counter += 1;
}
if (counter%100 == 0) {
var percentage = Math.round((counter/area)*100, 2);
console.log("Percentage: "+percentage+"%" + " "+counter);
}
width_counter += 1;
}
console.log(positions_clone.length);
console.log(area_grid.length);
areas[area_counter] = {'area': area_grid, 'positions': positions_clone};
parent.find('.area').text(area_counter);
area_counter += 1;
}
any clues in fixing it will be appreciated. I've showed how it behaves after commenting out certain parts of the code in the video.
Change
var index = positions.findIndex(function(item) {
to
var index = positions_clone.findIndex(function(item) {
Because after each splice, the indices of the original positions doesn't change but you are still using those indices to splice the clone.

My javascript canvas map script and poor performance

Basically below is my script for a prototype which uses 128x128 tiles to draw a map on a canvas which user can drag to move around.
Script does work. However I have a few problems to be solved:
1. Poor performance and I can't figure out why.
2. I am missing a method to buffer the tiles before the actual drawing.
3. If you notice any other issues also that could help me to make things run more smoothly it would be fantastic.
Some explanations for the script:
variables
coordinates - Defines the actual images to be displayed. Image file names are type of '0_1.jpg', where 0 is Y and 1 is X.
mouse_position - As name says, is keeping record of mouse position.
position - This is a poorly named variable. It defines the position of the context drawn on canvas. This changes when user drags the view.
Any assistance would be appreciated greatly. Thank you.
var coordinates = [0, 0];
var mouse_position = [0, 0];
var position = [-128, -128];
var canvas = document.getElementById('map_canvas');
var context = canvas.getContext('2d');
var buffer = [];
var buffer_x = Math.floor(window.innerWidth/128)+4;
var buffer_y = Math.floor(window.innerHeight/128)+4;
var animation_frame_request = function() {
var a = window.requestAnimationFrame;
var b = window.webkitRequestAnimationFrame;
var c = window.mozRequestAnimationFrame;
var d = function(callback) {
window.setTimeout(callback, 1000/60);
}
return a || b || c || d;
}
var resizeCanvas = function() {
window.canvas.width = window.innerWidth;
window.canvas.height = window.innerHeight;
window.buffer_x = Math.floor(window.innerWidth/128)+4;
window.buffer_y = Math.floor(window.innerHeight/128)+4;
window.buffer = [];
for (row = 0; row < window.buffer_y; row++) {
x = [];
for (col = 0; col < window.buffer_x; col++) {
x.push(new Image());
}
window.buffer.push(x);
}
}
var render = function() {
animation_frame_request(render);
for (row = 0; row < window.buffer_y; row++) {
for (col = 0; col < window.buffer_x; col++) {
cy = window.coordinates[1]+row;
cx = window.coordinates[0]+col;
window.buffer[row][col].src = 'map/'+cy+'_'+cx+'.jpg';
}
}
for (row = 0; row < window.buffer_y; row++) {
for (col = 0; col < window.buffer_x; col++) {
window.context.drawImage(window.buffer[row][col],
window.position[0]+col*128,
window.position[1]+row*128, 128, 128);
}
}
}
var events = function() {
window.canvas.onmousemove = function(e) {
if (e['buttons'] == 1) {
window.position[0] += (e.clientX-window.mouse_position[0]);
window.position[1] += (e.clientY-window.mouse_position[1]);
if (window.position[0] >= 0) {
window.position[0] = -128;
window.coordinates[0] -= 1;
} else if (window.position[0] < -128) {
window.position[0] = 0;
window.coordinates[0] += 1;
}
if (window.position[1] >= 0) {
window.position[1] = -128;
window.coordinates[1] -= 1;
} else if (window.position[1] < -128) {
window.position[1] = 0;
window.coordinates[1] += 1;
}
render();
}
window.mouse_position[0] = e.clientX;
window.mouse_position[1] = e.clientY;
}
}
window.addEventListener('resize', resizeCanvas, false);
window.addEventListener('load', resizeCanvas, false);
window.addEventListener('mousemove', events, false);
resizeCanvas();
To get better performance you should avoid changing the src of img nodes and move them around instead.
A simple way to minimize the number of img nodes handled and modified (except for screen positioning) is to use an LRU (Least Recently Used) cache.
Basically you keep a cache of last say 100 image nodes (they must be enough to cover at least one screen) by using a dictionary mapping the src url to a node object and also keeping them all in a doubly-linked list.
When a tile is required you first check in the cache, and if it's already there just move it to the front of LRU list and move the img coordinates, otherwise create a new node and set the source or, if you already hit the cache limit, reuse the last node in the doubly-linked list instead. In code:
function setTile(x, y, src) {
var t = cache[src];
if (!t) {
if (cache_count == MAXCACHE) {
t = lru_last;
t.prev.next = null;
lru_last = t.prev;
t.prev = t.next = null;
delete cache[t.src]
t.src = src;
t.img.src = src;
cache[t.src] = t;
} else {
t = { prev: null,
next: null,
img: document.createElement("img") };
t.src = src;
t.img.src = src;
t.img.className = "tile";
scr.appendChild(t.img);
cache[t.src] = t;
cache_count += 1;
}
} else {
if (t.prev) t.prev.next = t.next; else lru_first = t.next;
if (t.next) t.next.prev = t.prev; else lru_last = t.prev;
}
t.prev = null; t.next = lru_first;
if (t.next) t.next.prev = t; else lru_last = t;
lru_first = t;
t.img.style.left = x + "px";
t.img.style.top = y + "px";
scr.appendChild(t.img);
}
I'm also always appending the requested tile to the container so that it goes in front of all other existing tiles; this way I don't need to remove old tiles and they're simply left behind.
To update the screen I just iterate over all the tiles I need and request them:
function setView(x0, y0) {
var w = scr.offsetWidth;
var h = scr.offsetHeight;
var iy0 = y0 >> 7;
var ix0 = x0 >> 7;
for (var y=iy0; y*128 < y0+h; y++) {
for (var x=ix0; x*128 < x0+w; x++) {
setTile(x*128-x0, y*128-y0, "tile_" + y + "_" + x + ".jpg");
}
}
}
most of the time the setTile request will just update the x and y coordinates of an existing img tag, without changing anything else. At the same time no more than MAXCACHE image nodes will be present on the screen.
You can see a full working example in
http://raksy.dyndns.org/tiles/tiles.html

For Loop MovieClip Grid not showing on stage

So I'm a newbie and should obviously spend time in the tuts, but I'm looking for a quick answer. Basically, I've created a grid of movie clips with AS3. When I 'preview' the flash (as a flash or HTML) it shows up fine. Success. Yet, the stage remains empty.
Q1) Will the stage remain empty as I have used AS3 to dynamically 'draw' the grid of mc's? Or is there a slit of code I am missing to make this baby show up on the stage?
Q2) I've managed to use alpha to make the MC's 'fade' on hover - but I want to make them change color (to red) when hovered over. I've searched everywhere and can't seem to find the right script.
Here is my code:
var stage = new createjs.Stage("canvas");
var image = new createjs.Bitmap("images/square.png");
stage.addChild(image);
createjs.Ticker.addEventListener("tick", handleTick);
function handleTick(event) {
image.x += 10;
stage.update();
}
var x0:Number = 0;
var y0:Number = 0;
var nt:Number = 72;
var nc = 10;
var vd:Number = 12;
var hd:Number = 12;
for (var i = 1; i <= nt; i++) {
var mc = this.attachMovie("square", "square" + i, i);
var aprox = Math.floor((i - 1) / nc);
mc._x = x0 + hd * ((i - aprox * nc) - 1);
mc._y = y0 + aprox * vd;
mc.useHandCursor = true;
// fade in
mc.onRollOver = function()
{
this.onEnterFrame = function()
{
if (this._alpha > 0) {
this._alpha -= 10;
} else {
this._alpha = 0;
delete this.onEnterFrame;
}
};
};
// fade out
mc.onRollOut = function()
{
this.onEnterFrame = function()
{
if (this._alpha < 100) {
this._alpha += 10;
} else {
this._alpha = 100;
delete this.onEnterFrame;
}
};
};
}
Thanks in advance - sorry I am a noob.
This will never work. 1/3 of your code is in AS3, 2/3 in AS2. Considering you haven't been thrown any error, I assume you exported it as AS2.

I'm trying to stop snow script and clear the page after x seconds

How can I make the snow clear after a certain time. I've tried using variables and the calling a timeout which switches on to false and stops the makesnow() function but that doesn't seem to clear the page at all.
<script language="javascript">
ns6 = document.getElementById;
ns = document.layers;
ie = document.all;
/*******************[AccessCSS]***********************************/
function accessCSS(layerID) { //
if(ns6){ return document.getElementById(layerID).style;} //
else if(ie){ return document.all[layerID].style; } //
else if(ns){ return document.layers[layerID]; } //
}/***********************************************************/
/**************************[move Layer]*************************************/
function move(layer,x,y) { accessCSS(layer).left=x; accessCSS(layer).top = y; }
function browserBredde() {
if (window.innerWidth) return window.innerWidth;
else if (document.body.clientWidth) return document.body.clientWidth;
else return 1024;
}
function browserHoyde() {
if (window.innerHeight) return window.innerHeight;
else if (document.body.clientHeight) return document.body.clientHeight;
else return 800;
}
function makeDiv(objName,parentDiv,w,h,content,x,y,overfl,positionType)
{
// positionType could be 'absolute' or 'relative'
if (parentDiv==null) parentDiv='body';
var oDiv = document.createElement ("DIV");
oDiv.id = objName;
if (w) oDiv.style.width = w;
if (h) oDiv.style.height= h;
if (content) oDiv.innerHTML=content;
if (positionType==null) positionType="absolute";
oDiv.style.position = positionType;
if (x) oDiv.style.left=x; else oDiv.style.left=-2000;
if (y) oDiv.style.top=y; else oDiv.style.top=-2000;
if (overfl) oDiv.style.overflow=overfl; else oDiv.style.overflow="hidden";
eval(' document.'+parentDiv+'.appendChild (oDiv); ');
delete oDiv;
}
var snowC=0;
var x = new Array();
var y = new Array();
var speed = new Array();
var t=0;
var cC = new Array();
var ra = new Array();
function makeSnow() {
x[snowC] = Math.round(Math.random()*(browserBredde()-60));
y[snowC] = 10;
makeDiv("snow"+snowC,"body",32,32,'<img src="http://i693.photobucket.com/albums/vv296/KIBBLESGRAMMY/CAT/Orange-tabby-cat-icon.gif">');
speed[snowC] = Math.round(Math.random()*8)+1;
cC[snowC]=Math.random()*10;
ra[snowC] = Math.random()*7;
snowC++;
}
function moveSnow() {
var r = Math.round(Math.random()*100);
if (r>70 && snowC<20) makeSnow();
for (t=0;t<snowC;t++) {
y[t]+=speed[t];move("snow"+t,x[t],y[t]);
if (y[t]>browserHoyde()-50) {y[t] = 10;x[t] = Math.round(Math.random()*(browserBredde()-60));}
cC[t]+=0.01;
x[t]+=Math.cos(cC[t]*ra[t]);
}
setTimeout('moveSnow()',20);
}
moveSnow();
</script>
makeSnow just adds the snowflakes. Stopping that, as you say, does not clear anything. moveSnow handles the animation, and calls itself at a timeout. If instead of setting a timeout for the next moveSnow each time, you set it up to run in an interval just once, you would have an easier time stopping it.
window.snowAnimation = window.setInterval(moveSnow, 20);
If you add a css class to your snow flakes, it would be easier to target them for deletion.
oDiv.className = 'snowflake';
Then your clear function could look something like:
function clearSnow() {
window.clearTimeout(window.snowAnimation);
var flakes = document.getElementsByTagName('snowflake');
for(var i = 0, l = flakes.length; i < l; i++) {
document.body.removeChild(flakes[i]);
}
}
Timeout doesnt help, it helps you only to stop creating new snowdivs, however if you see makeDiv is the one which creates new divs on to the body, if you clear / display:none the divs which got created on makeDiv i hope it will clear all the divs on the screen.
You need to remove the divs that were created. It might be easier if you give them all some sort of class, like ".snowflake" as you create them (in makeDiv), then start removing them from the dom.
You will have to clear the elements created after the time you wanna stop snow falling.
Following code snippet will help you to clear the elements
if(count < 500){
setTimeout('moveSnow()',20);
}else{
var i = 0;
var elem = document.getElementById('snow'+i);
do{
elem.parentNode.removeChild(elem);
elem = document.getElementById('snow'+ ++i);
}while(elem != null)
}
count++;
you have to create a global variable count.

Categories

Resources