how to animate canvas using this plug in - javascript

Im still new to this type of programming, im trying to create kaledoscope kind of effect to be projected on screen. I want to make the image move isnide each section of the effect. is there a way to move it? i cant seem to target the canvas created by the plug in.
https://codepen.io/muspelheim/pen/gpymF
var images = [
"http://media-cache-ak0.pinimg.com/736x/5d/d8/41/5dd8416cbae27edeac61aa525a5df99d.jpg",
"https://1.bp.blogspot.com/-FpxaoVBBxXs/T5aWaP2dMDI/AAAAAAAAAw8/qdaPYyuqSt8/s1600/spugnaepicinfame.jpg",
"https://25.media.tumblr.com/tumblr_m9ls7nRTuR1rvqbato1_1280.jpg",
"https://3.bp.blogspot.com/-SJAKrZTcqwI/T5kwYk71YCI/AAAAAAAAAxE/HNlX3i2-xwk/s1600/spugnabimbofango.jpg"
];
// Let's create graphemescope object inside the container
var container = $("#container");
var scope = new Graphemescope( container[0] );
var index = 0;
function changePicture() {
scope.setImage(images[index]);
index = (index + 1) % images.length;
};
setInterval(changePicture, 2000);
changePicture();
$(window).mousemove(function(event) {
var factorx = event.pageX / $(window).width();
var factory = event.pageY / $(window).height()
// This will move kaleidoscope
scope.angleTarget = factorx;
scope.zoomTarget = 1.0 + 0.5 * factory;
});
var resizeHandler = function() {
container.height( $(window).height() );
container.width( $(window).width() );
};
$(window).resize(resizeHandler);
$(window).resize();
container.click(changePicture);

Related

From Paperscript to Javascript

I'm trying to convert one of the Paper.js library examples (http://paperjs.org/examples/smoothing/) from PaperScript to Javascript. Following the documentation, I have
Made the scope global
Installed the event handlers onFrame and onResize
Created a tool and installed the event handlers onMouseMove and onMouseDown
But the canvas is not shown. I only see a couple of small blue lines: AFAIK the problem lies in the view.onFrame() function, since commenting that out at least I can see the shape, but not interact with it. The JS console dosen't show any error. What is missing?
// Make the paper scope global, by injecting it into window
paper.install(window);
window.onload = function () {
// Setup directly from canvas id:
paper.setup('myCanvas');
// Create tool
tool = new Tool();
var width, height, center;
var points = 10;
var smooth = true;
var path = new Path();
var mousePos = view.center / 2;
var pathHeight = mousePos.y;
path.fillColor = 'black';
initializePath();
function initializePath() {
center = view.center;
width = view.size.width;
height = view.size.height / 2;
path.segments = [];
path.add(view.bounds.bottomLeft);
for (var i = 1; i < points; i++) {
var point = new Point(width / points * i, center.y);
path.add(point);
}
path.add(view.bounds.bottomRight);
path.fullySelected = true;
}
view.onFrame = function (event) {
pathHeight += (center.y - mousePos.y - pathHeight) / 10;
for (var i = 1; i < points; i++) {
var sinSeed = event.count + (i + i % 10) * 100;
var sinHeight = Math.sin(sinSeed / 200) * pathHeight;
var yPos = Math.sin(sinSeed / 100) * sinHeight + height;
path.segments[i].point.y = yPos;
}
if (smooth)
path.smooth({ type: 'continuous' });
}
tool.onMouseMove = function (event) {
mousePos = event.point;
}
tool.onMouseDown = function (event) {
smooth = !smooth;
if (!smooth) {
// If smooth has been turned off, we need to reset
// the handles of the path:
for (var i = 0, l = path.segments.length; i < l; i++) {
var segment = path.segments[i];
segment.handleIn = segment.handleOut = null;
}
}
}
// Reposition the path whenever the window is resized:
view.onResize = function (event) {
initializePath();
}
}
To try it: https://jsfiddle.net/1rtkbp9s/
Found the solution (credits to Stefan Krüger of the Paper.js Google Group):
var mousePos = view.center / 2;
Should have been:
var mousePos = view.center.divide(2);
The fact is that Math functions should be used instead of operators for Point and Size object... and I didn't realize that view.center IS a Point object: http://paperjs.org/reference/view/#center

Moving a box to a random position with angularjs

I am looking for a way to implement the exact functionality from this answer using angularjs: Specifically, for a box (div) to move randomly around a screen, while being animated. Currently I have tried
myApp.directive("ngSlider", function($window) {
return {
link: function(scope, element, attrs){
var animateDiv = function(newq) {
var oldRect = element.getBoundingClientRect();
var oldq = [oldRect.top, oldRect.left];
if (oldq != newq){
var dir = calcDir([oldq.top, oldq.left], newq);
element.moveTo(oldq.left + dir[0], oldq.top + dir[1]);
setTimeout(animateDiv(newq), 100);
}
};
var makeNewPosition = function() {
// Get viewport dimensions (remove the dimension of the div)
var window = angular.element($window);
var h = window.height() - 50;
var w = window.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
};
function calcDir(prev, next) {
var x = prev[1] - next[1];
var y = prev[0] - next[0];
var norm = Math.sqrt(x * x + y * y);
return [x/norm, y/norm];
}
var newq = makeNewPosition();
animateDiv(newq);
}
};
});
There appears to be quite a bit wrong with this, from an angular point of view. Any help is appreciated.
I like to take advantage of CSS in situations like this.
absolutely position your div
use ng-style to bind top and left attributes to some in-scope variable
randomly change the top and left attributes of this in-scope variable
use CSS transitions on top and left attributes to animate it for you
I made a plnkr! Visit Kentucky!

Anyway to optimise this parallax script for better performance?

I have a parallax script that I am using to slow the background position of an element relative to the window scroll. It performs GREAT on my macbook pro but on slower computers it shudders more than I feel it needs to.
Here is the code below:
var bgobj = $('.paral');
$(window).scroll(function () {
onScroll(bgobj);
});
function onScroll(bgobj) {
var $window = $(window);
var yPos = ($window.scrollTop() / bgobj.data('speed'));
// Put together our final background position
var coords = yPos + 'px';
// Move the background
bgobj.css({ backgroundPositionY: coords });
}
So my question is, what optimisations can be made to the code to improve speed on lower machines?
Thank you
Have you considered throttling?
http://underscorejs.org/#throttle
http://underscorejs.org/#debounce
var bgobj = $('.paral');
var onScrollThrottled = _.throttle(onScroll, 100);
$(window).scroll(function () {
onScrollThrottled(bgobj);
});
function onScroll(bgobj) {
var $window = $(window);
var yPos = ($window.scrollTop() / bgobj.data('speed'));
// Put together our final background position
var coords = yPos + 'px';
// Move the background
bgobj.css({ backgroundPositionY: coords });
if (isScrolledIntoView($('#more-info'))) {
animateCircle();
}
}
Of course, instead of throttling/debouncing the entire onScroll function you can apply the optimisation to animateCirle or updating the background css
I see some minor improvements to be done. Nothing big:
//cache $window and speed
var $window = $(window);
var bgobj = $('.paral');
var speed = bgobj.data('speed')
$window.scroll(function () {
onScroll(bgobj);
});
function onScroll(bgobj) {
var yPos = ($window.scrollTop() / speed);
// Put together our final background position
//var coords = yPos + 'px'; // this is not needad as jQuery defaults to pixels if nothing is specified
// Move the background
bgobj.css({ backgroundPositionY: coords });
if (isScrolledIntoView($('#more-info'))) { // depending on what is inside this function, this might slow everything doen
animateCircle();
}

Using the window resize function to keep variables uptodate?

I am a little confused on how to keep some variables Ive created uptodate when the window is resized so my scroll function carries on getting the correct values. Basically I have multiple elements that contain a message that gets displayed when the user scrolls the element into 50% height of the viewport height. This works fine but my issue is when I resize I'm not sure how to update my variables boxHeight, elementOffset, verticalMatch which keep control of the values I need to use in my scroll event. I was wondering can someone help explain how I can resolve this?
My code looks like this
var windowHeight = $(window).height(),
headerHeight = $('.header').height();
$('.box').each(function (i,e) {
var el = $(e);
var boxHeight = el.height(),
elementOffset = el.offset().top,
verticalMatch = (windowHeight / 2) + (headerHeight / 2) - (boxHeight / 2);
$(window).on('scroll', function () {
var scrollTop = $(window).scrollTop(),
distance = elementOffset - scrollTop;
if( distance <= verticalMatch ) {
el.addClass('is-active');
}
});
});
$(window).on('resize', function() {
windowHeight = $(window).height()
elementOffset = $('.box').offset().top;
$('.box').each(function (i,e) {
var el = $(e);
//update boxHeight, elementOffset, verticalMatch
verticalMatch = (windowHeight / 2) + (headerHeight / 2) - (boxHeight / 2);
});
});
And heres the JS Fiddle: http://jsfiddle.net/fm4z7/2/
If someone could explain how I do this it would be great!
If all you want to do is update your sizing variables during a resize event, then do just that:
$(window).on('resize', function() {
windowHeight = $(window).height();
elementOffset = $('.box').offset().top;
});
Your variables are global so they can be accessed anywhere.

Container height based on every 2 images row

I´m working on this website
I´m doing the resize of vertical images using this script:
function Gallery(selector) {
this.add_module = function (type, image) {
var portrait_text = image.next('.portrait_text');
var container = $('<div />', {
'class': 'gallery_container'
}).append(image).append(portrait_text);
if (type == 'horizontal') {
var h_ar = image.attr('height') / image.attr('width');
var c_width = selector.width();
var c_height = selector.width() * h_ar
container.css({
'width': c_width,
'height': c_height
})
}
if (type == 'vertical') {
var c_width = v_width;
var c_height = v_height
container.css({
'width': Math.floor(v_width),
'height': v_height
})
}
container.css({
'float': 'left',
})
container.find('img').attr({
'width': '100%',
'height': '100%'
})
container.attr('ar', c_height / c_width)
container.appendTo(selector);
//container.children('img').fitToBox();
}
this.resized = function () {
//console.log(sel)
$('.gallery_container').each(function () {
if ($(this).attr('ar') >= 1) { // vertical
$(this).css({
'width': sel.width() / 2,
'height': sel.width() / 2 * $(this).attr('ar')
})
} else { // horizontal
$(this).css({
'width': sel.width(),
'height': sel.width() * $(this).attr('ar')
})
}
})
}
var _this = this;
var gutter = 0;
// start vars for counting on vertical images
var v_counter = 0;
var w_pxls = 0;
var h_pxls = 0;
var v_ar;
// iterates through images looking for verticals
selector.children('img').each(function () {
if (parseInt($(this).attr('width')) < parseInt($(this).attr('height'))) {
v_counter++;
h_pxls += $(this).attr('height');
w_pxls += $(this).attr('width');
v_ar = $(this).attr('height') / $(this).attr('width')
}
})
// calculates average ar for vertical images (anything outside from aspect ratio will be croped)
var h_avrg = Math.floor(h_pxls / v_counter);
var w_avrg = Math.floor(w_pxls / v_counter);
var v_width = Math.floor((selector.width()) / 2);
var v_height = v_width * v_ar;
var sel = selector;
selector.children('img').each(function () {
if (parseInt($(this).attr('width')) > parseInt($(this).attr('height'))) {
_this.add_module('horizontal', $(this));
} else {
_this.add_module('vertical', $(this));
}
})
$(window).bind('resize', _this.resized);
}
var gallery = new Gallery($('#gallery_images_inner'));
http://jsfiddle.net/mZ2Ks/
The problem I have is that the script makes all the container the same of height (depending on the last image on the page I think), so for example first images resizes in a bad way. If you look at the example, all 2 image rows have a height of 613px.
Is there any way how can I control each two images container to calculate it´s own height based on its images, it looks like right now it calculates the last image resize height and apply it to all other containers
Applying height: auto instead of 100% won´t work cause it will not make the images fit the height of the vertical container.
How can I fix the script?
yes, there is a easy way. but frist: your gallery-script calculates a average aspect ratio for all images inside. there is no simple way to change this behavior.
But you can do this simple workaround: put echt two images in their own gallery!
var gallery1 = new Gallery($('#gallery_images_inner1'));
var gallery2 = new Gallery($('#gallery_images_inner2'));
var gallery3 = new Gallery($('#gallery_images_inner3'));
See http://jsfiddle.net/mZ2Ks/2/ - i had to clean up your html code a little bit - you copied the "javascript affected" html code from (i assume) firebug, but you should have copied the plain html from source code direct (CTRL + U in firefox).

Categories

Resources