Related
In my project I have some not static elements (as object1 in example) that have one sprite texture associated with them. Then I have another static element (change_sprites_object) where I want to click and change the sprites textures.
How can I achieve this in matter.js?
Example of my objects:
var x_object1 = 1370;
var y_object1 = 725;
var obj_properties = {
density: 0.0005,
frictionAir: 0.01,
restitution: 0.8,
friction: 0.01
};
var object1_properties = obj_properties;
jogo_properties.render = {
sprite: {
texture: 'images/object1.png'
}
};
object1 = Bodies.circle(x_object1, y_object1, 113, object1_properties);
change_sprites_object = Bodies.rectangle(1680, 1005, 77, 50, {
isStatic: true,
render: {
sprite: {
texture: 'images/change_sprites_object.png'
}
}
});
var flag = 0;
var element = document.getElementsByTagName('canvas')[0];
//verify if it's a click or drag
element.addEventListener("mousedown", function () {
flag = 0;
}, false);
element.addEventListener("mousemove", function () {
flag = 1;
}, false);
element.addEventListener("mouseup", function () {
if (flag === 0) {
var mouse = mouseConstraint.mouse;
if (Bounds.contains(change_sprites_object.bounds, mouse.position) {
//change object1 sprite
}...
I have a very strange behaviour of my script: only from time to time (seldom 3-4 times at one time right after each other, but more likely every 7th to 150th trial) the skript loads, but I only see a white canvas and get the error message:
Uncaught TypeError: Cannot read property 'getParent' of
undefinedKonva.Util.addMethods.add # konva.min.js:44draw #
floorplansurvey.php:950(anonymous function) #
floorplansurvey.php:985images.(anonymous function).onload #
floorplansurvey.php:390
On reload it often works again...
I just have no idea at all what is happening here, the bug can't be forced/reproduced, I thank you so much, if you have anything you can help me with. Even a strategy for a clearer analysis would be helpful, sorry for being that unspecific and the long code
edit: I've made a jsfiddle under:
https://jsfiddle.net/17548hmv/1/
run it several times, until the error occures
these are the code snippets at:
# floorplansurvey.php:390:
function loadImages(sources, draw) {
//window.location.reload(true);
var images = {};
var loadedImages = 0;
var numImages = 0;
// get num of sources
for(var src in sources) {
numImages++;
}
for(var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if(++loadedImages >= numImages) {
draw(images);
}
};
images[src].src = sources[src];
}
delete (loadedImages);
delete (numImages);
};
# floorplansurvey.php:985images.(anonymous function).onload:
loadImages(sources, function(images) {
draw(images);
});
# floorplansurvey.php:950(anonymous function):
bglayer.add(plan);
# konva.min.js:44draw:
I dont understand this one myself
add:function(t)
{if(arguments.length>1)
{for(var e=0;e<arguments.length;e++)
this.add(arguments[e]);
return this}if(t.getParent())return t.moveTo(this),this;
var n=this.children;
return
Var sources is defined like:
var sources = {
Cd: './graphics/Cd.png',
Cu: './graphics/Cu.png',
Ca: './graphics/Ca.png',
Cs: './graphics/Cs.png',
Cc: './graphics/Cc.png',
Ed: './graphics/Ed.png',
Eu: './graphics/Eu.png',
Ea: './graphics/Ea.png',
Es: './graphics/Es.png',
Ec: './graphics/Ec.png',
Hd: './graphics/Hd.png',
Hu: './graphics/Hu.png',
...and so on
and this is the function draw:
function draw(images) {
for (i=0, len=showdatax.length; i<=len-1; i++)
{
//window.location.reload(true);
var gridcell = new Konva.Rect({
x: parseInt((imagesizeX - showdatax[i])*scalar-(gridcellsize/2)),
y: parseInt((imagesizeY - showdatay[i])*scalar-(gridcellsize/2)),
offset: [0, 0],
width: gridcellsize,
height: gridcellsize,
//fill: 'white',
//stroke: 'grey',
//strokeWidth: 2,
draggable: false,
id: showdatav[i]
});
gridlayer.add(gridcell);
}
//defaultsettiongs
var init = new Array();
init['x'] = new Array();
init['y'] = new Array();
init['x']['c'] = 0*scalar;
init['y']['c'] = 170*scalar;
init['x']['e'] = 0*scalar;
init['y']['e'] = 320*scalar;
init['x']['h'] = 0*scalar;
init['y']['h'] = 470*scalar;
init['x']['l'] = 0*scalar;
init['y']['l'] = 620*scalar;
init['x']['s'] = 0*scalar;
init['y']['s'] = 770*scalar;
init['x']['w'] = 0*scalar;
init['y']['w'] = 920*scalar; var step = 0;
var count = new Array (
'c','e','h','l','s','w');
count['c'] = 0;
count['e'] = 0;
count['h'] = 0;
count['l'] = 0;
count['s'] = 0;
count['w'] = 0;
var starttime = new Date();
var loghistory = '';
//drag event functions
function mouseoverbox (box,active)
{
writeMessage('Click and hold the left mouse button and pull this activity icon to the floorplan.');
box.setFillPatternImage(active);
box.shadowColor('blue');
box.moveTo(templayer);
badgelayer.draw();
templayer.draw();
}
function dragstarttouchstartbox (box,pos,kind)
{
//count[kind]++;
writeMessage('dragstart' + count[kind]);
var boxx = box.x;
box.x(pos.x-1.5*gridcellsize);
var boxy = box.y;
box.y(pos.y-1.5*gridcellsize);
var boxrshadowoffsetx = box.shadowOffset();
box.shadowOffset({x:0.25*gridcellsize,y:0.25*gridcellsize});
box.moveTo(templayer);
badgelayer.draw();
templayer.draw();
}
function dragmovebox (box,pos,kind,success,active,caution)
{
writeMessage('Your outside of the floorplan. Dropping the activity icon will reset it to its initial position.');
box.moveTo(templayer);
var boxx = box.x;
box.x(pos.x-1.5*gridcellsize);
var boxy = box.y;
box.y(pos.y-1.5*gridcellsize);
var shape = gridlayer.getIntersection(pos);
if (shape)
{
if (!badgelayer.getIntersection(pos))
{
writeMessage('Release the mouse button to place this activity icon on position (' + shape.x() + '|' + shape.y() + ')');
box.x(shape.x()-gridcellsize);
box.y(shape.y()-gridcellsize);
box.setFillPatternImage(success);
box.shadowColor('green');
badgelayer.draw();
}
else
{
writeMessage('Position (' + shape.x() + '|' + shape.y() + ') is in use!!! Can\'t allocate second activiy icon here.');
var boxx = box.x;
box.x(pos.x-1.5*gridcellsize);
var boxy = box.y;
box.y(pos.y-1.5*gridcellsize);
box.setFillPatternImage(caution);
box.shadowColor('red');
badgelayer.draw();
}
}
else
{
box.setFillPatternImage(active);
box.shadowColor('blue');
templayer.draw();
badgelayer.draw();
}
}
function dragendtouchendbox (box,pos,kind,caution,defaultimage)
{
var shape = gridlayer.getIntersection(pos);
box.moveTo(badgelayer);
templayer.draw();
if (shape && !(badgelayer.getIntersection(pos)))
{
writeMessage('Activity icon successfully placed at position (' + shape.x() + '|' + shape.y() + ').');
box.shadowOffset({x:0,y:0});
box.shadowColor('green');
}
else
{
box.shadowColor('red');
box.setFillPatternImage(caution);
badgelayer.draw();
var fromouttween = new Konva.Tween
({
node: box,
x: init['x'][kind]+imagesizeX*scalar+ gridcellsize,
y: init['y'][kind],
easing: Konva.Easings['EaseOut'],
duration: 0.3
});
if (!shape)
{
writeMessage('Please drop the activity icons inside the floorplan.');
}
else if (badgelayer.getIntersection(pos))
{
writeMessage('Please don\'t drop the activity icons onto a used place.');
}
fromouttween.play();
box.shadowColor('black');
box.setFillPatternImage(defaultimage);
box.shadowOffset({x:0,y:0});
badgelayer.draw();
pos.x=-100;
pos.y=-100;
}
count['kind']++;
step++;
writeResultToForm(pos,count,kind,step,loghistory,starttime);
badgelayer.draw();
templayer.draw();
//writeMessage('dragend');
}
function mouseoutbox (box,defaultimage)
{
box.setFillPatternImage(defaultimage);
box.moveTo(badgelayer);
box.shadowColor('black');
if (!validateForm(false))
{
writeMessage('There are still activity icons left to place.');
}
else
{
writeMessage('All activity icons are placed successfully. You can click "continue" now or change your placements.');
}
badgelayer.draw();
templayer.draw();
}
function alertbox (box,caution)
{
box.setFillPatternImage(caution);
box.shadowcolor('red');
badgelayer.draw;
}
//cbox and text
var textc = new Konva.Text({
x: init['x']['c']+imagesizeX*scalar+gridcellsize*5,
y: init['y']['c']+gridcellsize,
text: 'Cooking',
align: 'left',
width: badgetextwidth
});
var boxc = new Konva.Rect({
x: init['x']['c']+imagesizeX*scalar+gridcellsize,
y: init['y']['c'],
offset: [0, 0],
width: 3*gridcellsize,
height: 3*gridcellsize,
fillPatternImage: images.Cd,
fillPatternScaleX: scalar,
fillPatternScaleY: scalar,
stroke: 'black',
strokeWidth: 4,
draggable: true,
cornerRadius: gridcellsize/2,
shadowColor: 'black',
shadowBlur: 10,
shadowOffset: {x : 0, y : 0},
shadowOpacity: 0.5
});
var boxcd = new Konva.Rect({
x: init['x']['c']+imagesizeX*scalar+gridcellsize,
y: init['y']['c'],
offset: [0, 0],
width: 3*gridcellsize,
height: 3*gridcellsize,
fillPatternImage: images.Cu,
fillPatternScaleX: scalar,
fillPatternScaleY: scalar,
stroke: 'grey',
strokeWidth: 2,
draggable: false,
cornerRadius: gridcellsize/2,
});
boxc.on('mouseover ', function() {
mouseoverbox (this,images.Ca);
});
boxc.on('dragstart', function() {
var pos = stage.getPointerPosition();
dragstarttouchstartbox (this,pos,'c');
});
boxc.on('dragmove', function () {
var pos = stage.getPointerPosition();
dragmovebox(this,pos,'c',images.Cs,images.Ca,images.Cc);
});
boxc.on('dragend', function() {
var pos = stage.getPointerPosition();
dragendtouchendbox (this,pos,'c',images.Cc,images.Cd);
});
boxc.on('mouseout ', function() {
mouseoutbox (this,images.Cd)
});
boxc.on('foo', function() {
alertbox (this,images.Cd)
});
//ebox and text
var texte = new Konva.Text({
x: init['x']['e']+imagesizeX*scalar+gridcellsize*5,
...and so on for all the boxes addes here (5 times as long):
defaultlayer.add(boxcd);
badgelayer.add(boxc);
defaultlayer.add(textc);
defaultlayer.add(boxed);
badgelayer.add(boxe);
defaultlayer.add(texte);
defaultlayer.add(boxhd);
badgelayer.add(boxh);
defaultlayer.add(texth);
defaultlayer.add(boxld);
badgelayer.add(boxl);
defaultlayer.add(textl);
defaultlayer.add(boxsd);
badgelayer.add(boxs);
defaultlayer.add(texts);
defaultlayer.add(boxwd);
badgelayer.add(boxw);
defaultlayer.add(textw);
stage.add(bglayer);
stage.add(gridlayer);
stage.add(defaultlayer);
stage.add(badgelayer);
stage.add(templayer);
}
OK, sorry that it took me so long:
the solution wasn't that easy to find. I found that the script was loaded asynchronously and the png wasn't yet available by using chromes timeline analysis. so i went to my code and had to distinguish between the things, that really should be in the draw function and which not. i added the plan to the array of images (sources) that is loaded (src= ...) before executing draw() and then added
sources.onload= loadImages(sources, function(images) {
draw(images);
});
at the end of my file... no it works without any problem. konva.js had nothing to do with it and is up to now (I'm almost ready) like designed for my project
thanks for the tip #lavrton, it took me on the right way
and you can just put like this:
var imageObj = new Image();
imageObj.src = 'http://localhost:8000/plugins/kamiyar/logo.png';
imageObj.onload = function() {
var img = new Konva.Image({
image: imageObj,
x: stage.getWidth() / 2 - 200 / 2,
y: stage.getHeight() / 2 - 137 / 2,
width: 200,
height: 137,
draggable: true,
stroke: 'blue',
strokeWidth: 1,
dash: [1,5],
strokeEnabled: false
});
layer.add(img);
layer.draw();
};
sorry for my bad English ;)
I need help for the slider on TweenMax.js
The problem:
This example has 4 images, on click each images will open in a fullscreen.
But i am not getting the previous screen link and next screen link in fullscreen.
Expected Result: once image is clicked, it should get previous image hyperlink and next hyperlink in all the sliders
Please Note : Now it is working for last image and first image.
even though i click any image
Please accept my apologies, CODE is very big !
JSFIDDLE :
http://jsfiddle.net/goo08gg5/11/
Any help is appreciated, thanks in advance.
UPDATE:
I feel this place in JS, we need to make the changes, but i might be wrong
//next image link
TweenLite.set($expander_nav.last(), {
x : 160,
right : 4,
left : 'auto',
delay : delay
});
//first image link
TweenLite.set($expander_nav.first(), {
x : -160,
left : 4,
right : 'auto',
delay : delay,
onComplete : function () {
// add content to title overlay after delay
$title.html(self.$cur_circle.siblings('.tagline').html());
}
});
JAVASCRIPT
var HeroCircles = function(el) {
this.$el = $(el);
this.$circles = this.$el.find('.circle');
this.$expander = this.$el.find('.circle-expander');
this.$cur_circle = null;
};
HeroCircles.prototype._placeBG = function() {
// get parent position and dimensions
var self = this,
parent_pos = this.$el.offset(),
parent_width = this.$el.width(),
parent_height = this.$el.height();
this.$circles.each(function() {
var $circle = $(this),
offset = $circle.offset(),
$bg = $circle.children('.bg');
// set position
$bg.css({
'top': parent_pos.top - offset.top + 'px',
'left': parent_pos.left - offset.left + 'px',
'width': parent_width + 'px',
'height': parent_height + 'px'
});
});
};
HeroCircles.prototype._animateInTitle = function(delay) {
var self = this,
$title = this.$expander.children('.title-overlay'),
cur_class = this.$cur_circle.data('name'),
$expander_nav = this.$expander.children('.expander-nav').children('a').not('.' + cur_class);
TweenLite.set($expander_nav.last(), { x: 160, right: 4, left: 'auto', delay: delay });
//Last image
TweenLite.set($expander_nav.first(), {
x: -160,
left: 4,
right: 'auto',
delay: delay,
onComplete: function() {
// add content to title overlay after delay
$title.html(self.$cur_circle.siblings('.tagline').html());
}
});
//Firstimage
// animate in title overlay
TweenLite.to($title, 0.5, {
y: 40,
delay: delay,
ease: Back.easeOut
});
TweenLite.to($expander_nav, 0.15, {
x: 0,
delay: delay + 0.5
});
};
HeroCircles.prototype._animateOutTitle = function() {
var $title = this.$expander.children('.title-overlay'),
cur_class = this.$cur_circle.data('name'),
$expander_nav = this.$expander.children('.expander-nav').children('a').not('.' + cur_class);
// animate out title overlay
TweenLite.to($title, 0.5, {
y: $title.outerHeight()
});
// animate out circles
TweenLite.to($expander_nav.first(), 0.15, {
x: -160
});
TweenLite.to($expander_nav.last(), 0.15, {
x: 160
});
};
HeroCircles.prototype._animateIn = function(circle) {
var $circle = $(circle),
$border = $circle.siblings('.border'),
img = $circle.children('.bg').data('bg');
// set current circle
this.$cur_circle = $circle;
// set bg image for expander div
this.$expander.css('z-index', 4);
this.$expander.children('.bg').css('background-image', 'url(' + img + ')');
// add active class to li
$circle.parent('li').addClass('active');
// expand circle
TweenLite.to($border, 0.3, {
scale: 7
});
// fade in expander
TweenLite.to(this.$expander, 0.5, {
opacity: 1,
delay: 0.5,
onComplete: function() {
TweenLite.set($border, { scale: 1 });
}
});
// animate in title overlay
this._animateInTitle(1);
};
HeroCircles.prototype._animateOut = function() {
var self = this;
// remove active class and scale down border
this.$el.find('li').removeClass('active');
// animate out title
this._animateOutTitle();
// fade out expander
TweenLite.to(this.$expander, 0.5, {
opacity: 0,
delay: 0.5,
onComplete: function() {
self.$expander.css({
'z-index': -1
});
}
});
};
HeroCircles.prototype._animateSwitch = function(circle) {
this._animateOutTitle();
this.$cur_circle = $(circle);
var img = this.$cur_circle.children('.bg').data('bg'),
$bg = this.$expander.children('.bg');
// switch active class
this.$el.find('li').removeClass('active');
this.$cur_circle.parent('li').addClass('active');
TweenLite.to($bg, 0.3, {
opacity: 0,
delay: 0.5,
onComplete: function() {
$bg.css('background-image', 'url(' + img + ')');
TweenLite.to($bg, 0.3, { opacity: 1 });
}
});
this._animateInTitle(1);
};
HeroCircles.prototype.init = function() {
var self = this;
this._placeBG();
// add click events
this.$el.on('click', '.circle', function() {
self._animateIn(this);
});
this.$el.find('.close-btn').on('click', function(e) {
e.preventDefault();
self._animateOut();
});
this.$expander.children('.expander-nav').on('click', 'a', function(e) {
e.preventDefault();
var new_class = $(this).attr('class'),
$circle = self.$el.find('ul .' + new_class);
console.log("new class is", new_class, "new circle is", $circle[0]);
self._animateSwitch($circle);
});
};
HeroCircles.prototype.initMobile = function() {
var self = this,
$mobile_slider = this.$el.find('.mobile-slider');
this.$el.on('click', '.circle', function() {
var $this = $(this),
bg = $this.children('.bg').data('bg');
self.$circles.removeClass('active');
$this.addClass('active');
$mobile_slider.html('<div>' + $this.siblings('.tagline').html() + '</div>');
$mobile_slider.css('background-image', 'url(' + bg + ')');
});
this.$circles.first().trigger('click');
};
var hero_circles = new HeroCircles('.hero-circles');
if ( window.innerWidth > 580 ) {
hero_circles.init();
} else {
hero_circles.initMobile();
}
I have make
Expected Result: once image is clicked, it should get previous image
hyperlink and next hyperlink in all the sliders
But i dont know how work this fadeIn and fadeOut circle.
This script work fine for next and prev slide, but the animation slide is no good. but it's work !
I have add a index of clicked circle for next and prev slide.
please see: http://jsfiddle.net/gw4eqg92/
I'm having trouble performing a simple rotation animation using jquery's animate method. I am trying to start a square at 45 degrees rotation and then, when clicking a button, rotate the square another 45 degrees (to complete at 90).
However, when I attempt the animation, the square first jerks back to a rotation of 0 before starting to progress towards its final completion point (90 degrees).
This appears to be because the "now" argument of animate()'s "step" option is starting at 0, rather than the actual starting point of the element, 45 degrees.
Any thoughts on what I'm doing wrong here?
http://jsfiddle.net/agentfitz/btz89/2/
// css
.square {
transform: rotate(45deg); // starting point
}
// js
$(".square").animate(
{
rotation: 90,
},
{
step: function(now, tween) {
var $el = $(this);
if (tween.prop === "rotation") {
console.log(now);
$el.css('transform','rotate('+now+'deg)');
}
},
duration: 2000
}
);
Please follow this example: http://jqversion.com/#!/1GLob7P
Javascript code:
$("a").click(function(e){
e.preventDefault();
var initRotation = 0;
$(".square").animate(
{
rotation: 45, // how many degrees do you want to rotate
},
{
start: function(promise){
initRotation = getRotationDegrees($(this));
},
step: function(now, tween) {
var $el = $(this);
if (tween.prop === "rotation") {
var newRotation = initRotation + now;
$el.css('-webkit-transform','rotate('+newRotation+'deg)');
$el.css('-moz-transform','rotate('+newRotation+'deg)');
$el.css('transform','rotate('+newRotation+'deg)');
}
},
duration: 2000
}
);
});
function getRotationDegrees(obj) {
var matrix = obj.css("-webkit-transform") ||
obj.css("-moz-transform") ||
obj.css("-ms-transform") ||
obj.css("-o-transform") ||
obj.css("transform");
if(matrix !== 'none') {
var values = matrix.split('(')[1].split(')')[0].split(',');
var a = values[0];
var b = values[1];
var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
} else { var angle = 0; }
return (angle < 0) ? angle +=360 : angle;
}
You can use start option to customize property start value:
// css
.square {
transform: rotate(45deg); // starting point
}
// js
var startRotation = 45;
$(".square").animate(
{
rotation: 90,
},
{
start: function(promise) {
for (var i = 0; i < promise.tweens.length; i++) {
var tween = promise.tweens[i];
if (tween.prop === "rotation") {
tween.start = startRotation;
}
}
},
step: function(now, tween) {
var $el = $(this);
if (tween.prop === "rotation") {
console.log(now);
$el.css('transform','rotate('+now+'deg)');
}
},
duration: 2000
}
);
I have some icons from Raphaƫl.js, and I would like to fade them in sequentially on page load.
Here I build the icons:
function navBar() {
var icon={/* lots of path strings */},
fill = {
fill:"#666",
stroke:"none",
opacity:0 // opacity is initially 0; would like to loop through this
},
stroke = {
stroke:"#fff",
"stroke-width":3,
"stroke-linejoin":"round",
opacity:0
};
for (var name in icon) {
var r = Raphael(0, 0, 40, 40),
s = r.path(icon[name]).attr(stroke).translate(4, 4),
Icon = r.path(icon[name]).attr(fill).translate(4, 4),
Path = document.getElementById("path"),
none = {fill: "#000", opacity: 0};
(function (icon, path, s, name) {
r.rect(0, 0, 38, 38).attr(none).hover(function () {
s.stop().animate({opacity: 1}, 200);
}, function () {
s.stop().attr({opacity: 0});
});
})(Icon, icon[name], s, name);
// Here I'm able to fade all of the icons in at the same time
(function (icon) {
Icon.animate({opacity:1},200);
})(Icon);
}
}
Rather than fade all of the icons in at the same time as I've done at the end of the script, how can I loop through them and fade them each in, one by one, with a slight delay in between?
Maybe you need to animate them after create opr. is done. Here is a simulation: http://jsfiddle.net/r75hh/
Like this or so.
// creating
var icon = new Raphael ...
...
icon.attr("rel", "icon")
// the last line in navBar()
animateIcons();
// animating
function animateIcons() {
// assuming jQuery in use
var icons = $("elementTagNameOfIcon[rel='icon']");
var i = 0;
var f = function(){
var icon = icons.get(i);
if (icon) {
$(icon).animate({opacity:1}, 200, function(){
f();
});
i++;
}
};
f();
}