I'm using a slideshow script in my site. I'm new to javascript. I want one thing.
When i put the mouse over a slide, it should pause on the picture, and not keep changing.
I'm using mootools.
Slideshow link
var gallery = {
initialize: function(element, options) {
this.setOptions({
showArrows: true,
showCarousel: true,
showInfopane: true,
embedLinks: true,
fadeDuration: 500,
timed: false,
delay: 5000,
preloader: true,
preloaderImage: true,
preloaderErrorImage: true,
/* Data retrieval */
manualData: [],
populateFrom: false,
populateData: true,
destroyAfterPopulate: true,
elementSelector: "div.imageElement",
titleSelector: "h3",
subtitleSelector: "p",
linkSelector: "a.open",
imageSelector: "img.full",
thumbnailSelector: "img.thumbnail",
defaultTransition: "fade",
/* InfoPane options */
slideInfoZoneOpacity: 0.7,
slideInfoZoneSlide: true,
/* Carousel options */
carouselMinimizedOpacity: 0.4,
carouselMinimizedHeight: 20,
carouselMaximizedOpacity: 0.9,
thumbHeight: 75,
thumbWidth: 100,
thumbSpacing: 10,
thumbIdleOpacity: 0.2,
textShowCarousel: 'Overview',
showCarouselLabel: true,
thumbCloseCarousel: false,
useThumbGenerator: false,
thumbGenerator: 'resizer.php',
useExternalCarousel: false,
carouselElement: false,
carouselHorizontal: true,
activateCarouselScroller: true,
carouselPreloader: true,
textPreloadingCarousel: 'Loading...',
/* CSS Classes */
baseClass: 'jdGallery',
withArrowsClass: 'withArrows',
/* Plugins: HistoryManager */
useHistoryManager: false,
paused: false,
customHistoryKey: false
}, options);
this.fireEvent('onInit');
this.currentIter = 0;
this.lastIter = 0;
this.maxIter = 0;
this.galleryElement = element;
this.galleryData = this.options.manualData;
this.galleryInit = 1;
this.galleryElements = Array();
this.thumbnailElements = Array();
this.galleryElement.addClass(this.options.baseClass);
this.populateFrom = element;
if (this.options.populateFrom)
this.populateFrom = this.options.populateFrom;
if (this.options.populateData)
this.populateData();
element.style.display="block";
if (this.options.useHistoryManager)
this.initHistory();
if (this.options.embedLinks)
{
this.currentLink = new Element('a').addClass('open').setProperties({
href: '#',
title: ''
}).injectInside(element);
if ((!this.options.showArrows) && (!this.options.showCarousel))
this.galleryElement = element = this.currentLink;
else
this.currentLink.setStyle('display', 'none');
}
this.constructElements();
if ((this.galleryData.length>1)&&(this.options.showArrows))
{
var leftArrow = new Element('a').addClass('left').addEvent(
'click',
this.prevItem.bind(this)
).injectInside(element);
var rightArrow = new Element('a').addClass('right').addEvent(
'click',
this.nextItem.bind(this)
).injectInside(element);
this.galleryElement.addClass(this.options.withArrowsClass);
}
this.loadingElement = new Element('div').addClass('loadingElement').injectInside(element);
if (this.options.showInfopane) this.initInfoSlideshow();
if (this.options.showCarousel) this.initCarousel();
this.doSlideShow(1);
},
populateData: function() {
currentArrayPlace = this.galleryData.length;
options = this.options;
var data = $A(this.galleryData);
data.extend(this.populateGallery(this.populateFrom, currentArrayPlace));
this.galleryData = data;
this.fireEvent('onPopulated');
},
populateGallery: function(element, startNumber) {
var data = [];
options = this.options;
currentArrayPlace = startNumber;
element.getElements(options.elementSelector).each(function(el) {
elementDict = {
image: el.getElement(options.imageSelector).getProperty('src'),
number: currentArrayPlace,
transition: this.options.defaultTransition
};
elementDict.extend = $extend;
if ((options.showInfopane) | (options.showCarousel))
elementDict.extend({
title: el.getElement(options.titleSelector).innerHTML,
description: el.getElement(options.subtitleSelector).innerHTML
});
if (options.embedLinks)
elementDict.extend({
link: el.getElement(options.linkSelector).href||false,
linkTitle: el.getElement(options.linkSelector).title||false,
linkTarget: el.getElement(options.linkSelector).getProperty('target')||false
});
if ((!options.useThumbGenerator) && (options.showCarousel))
elementDict.extend({
thumbnail: el.getElement(options.thumbnailSelector).getProperty('src')
});
else if (options.useThumbGenerator)
elementDict.extend({
thumbnail: options.thumbGenerator + '?imgfile=' + elementDict.image + '&max_width=' + options.thumbWidth + '&max_height=' + options.thumbHeight
});
data.extend([elementDict]);
currentArrayPlace++;
if (this.options.destroyAfterPopulate)
el.remove();
});
return data;
},
constructElements: function() {
el = this.galleryElement;
this.maxIter = this.galleryData.length;
var currentImg;
for(i=0;i<this.galleryData.length;i++)
{
var currentImg = new Fx.Styles(
new Element('div').addClass('slideElement').setStyles({
'position':'absolute',
'left':'0px',
'right':'0px',
'margin':'0px',
'padding':'0px',
'backgroundPosition':"center center",
'opacity':'0'
}).injectInside(el),
'opacity',
{duration: this.options.fadeDuration}
);
if (this.options.preloader)
{
currentImg.source = this.galleryData[i].image;
currentImg.loaded = false;
currentImg.load = function(imageStyle) {
if (!imageStyle.loaded) {
new Asset.image(imageStyle.source, {
'onload' : function(img){
img.element.setStyle(
'backgroundImage',
"url('" + img.source + "')")
img.loaded = true;
}.bind(this, imageStyle)
});
}
}.pass(currentImg, this);
} else {
currentImg.element.setStyle('backgroundImage',
"url('" + this.galleryData[i].image + "')");
}
this.galleryElements[parseInt(i)] = currentImg;
}
},
destroySlideShow: function(element) {
var myClassName = element.className;
var newElement = new Element('div').addClass('myClassName');
element.parentNode.replaceChild(newElement, element);
},
startSlideShow: function() {
this.fireEvent('onStart');
this.loadingElement.style.display = "none";
this.lastIter = this.maxIter - 1;
this.currentIter = 0;
this.galleryInit = 0;
this.galleryElements[parseInt(this.currentIter)].set({opacity: 1});
if (this.options.showInfopane)
this.showInfoSlideShow.delay(1000, this);
var textShowCarousel = formatString(this.options.textShowCarousel, this.currentIter+1, this.maxIter);
if (this.options.showCarousel&&(!this.options.carouselPreloader))
this.carouselBtn.setHTML(textShowCarousel).setProperty('title', textShowCarousel);
this.prepareTimer();
if (this.options.embedLinks)
this.makeLink(this.currentIter);
},
nextItem: function() {
this.fireEvent('onNextCalled');
this.nextIter = this.currentIter+1;
if (this.nextIter >= this.maxIter)
this.nextIter = 0;
this.galleryInit = 0;
this.goTo(this.nextIter);
},
prevItem: function() {
this.fireEvent('onPreviousCalled');
this.nextIter = this.currentIter-1;
if (this.nextIter <= -1)
this.nextIter = this.maxIter - 1;
this.galleryInit = 0;
this.goTo(this.nextIter);
},
goTo: function(num) {
this.clearTimer();
if(this.options.preloader)
{
this.galleryElements[num].load();
if (num==0)
this.galleryElements[this.maxIter - 1].load();
else
this.galleryElements[num - 1].load();
if (num==(this.maxIter - 1))
this.galleryElements[0].load();
else
this.galleryElements[num + 1].load();
}
if (this.options.embedLinks)
this.clearLink();
if (this.options.showInfopane)
{
this.slideInfoZone.clearChain();
this.hideInfoSlideShow().chain(this.changeItem.pass(num, this));
} else
this.currentChangeDelay = this.changeItem.delay(500, this, num);
if (this.options.embedLinks)
this.makeLink(num);
this.prepareTimer();
/*if (this.options.showCarousel)
this.clearThumbnailsHighlights();*/
},
changeItem: function(num) {
this.fireEvent('onStartChanging');
this.galleryInit = 0;
if (this.currentIter != num)
{
for(i=0;i<this.maxIter;i++)
{
if ((i != this.currentIter)) this.galleryElements[i].set({opacity: 0});
}
gallery.Transitions[this.galleryData[num].transition].pass([
this.galleryElements[this.currentIter],
this.galleryElements[num],
this.currentIter,
num], this)();
this.currentIter = num;
}
var textShowCarousel = formatString(this.options.textShowCarousel, num+1, this.maxIter);
if (this.options.showCarousel)
this.carouselBtn.setHTML(textShowCarousel).setProperty('title', textShowCarousel);
this.doSlideShow.bind(this)();
this.fireEvent('onChanged');
},
clearTimer: function() {
if (this.options.timed)
$clear(this.timer);
},
prepareTimer: function() {
if (this.options.timed)
this.timer = this.nextItem.delay(this.options.delay, this);
},
doSlideShow: function(position) {
if (this.galleryInit == 1)
{
imgPreloader = new Image();
imgPreloader.onload=function(){
this.startSlideShow.delay(10, this);
}.bind(this);
imgPreloader.src = this.galleryData[0].image;
if(this.options.preloader)
this.galleryElements[0].load();
} else {
if (this.options.showInfopane)
{
if (this.options.showInfopane)
{
this.showInfoSlideShow.delay((500 + this.options.fadeDuration), this);
} else
if ((this.options.showCarousel)&&(this.options.activateCarouselScroller))
this.centerCarouselOn(position);
}
}
},
createCarousel: function() {
var carouselElement;
if (!this.options.useExternalCarousel)
{
var carouselContainerElement = new Element('div').addClass('carouselContainer').injectInside(this.galleryElement);
this.carouselContainer = new Fx.Styles(carouselContainerElement, {transition: Fx.Transitions.expoOut});
this.carouselContainer.normalHeight = carouselContainerElement.offsetHeight;
this.carouselContainer.set({'opacity': this.options.carouselMinimizedOpacity, 'top': (this.options.carouselMinimizedHeight - this.carouselContainer.normalHeight)});
this.carouselBtn = new Element('a').addClass('carouselBtn').setProperties({
title: this.options.textShowCarousel
}).injectInside(carouselContainerElement);
if(this.options.carouselPreloader)
this.carouselBtn.setHTML(this.options.textPreloadingCarousel);
else
this.carouselBtn.setHTML(this.options.textShowCarousel);
this.carouselBtn.addEvent(
'click',
function () {
this.carouselContainer.clearTimer();
this.toggleCarousel();
}.bind(this)
);
this.carouselActive = false;
carouselElement = new Element('div').addClass('carousel').injectInside(carouselContainerElement);
this.carousel = new Fx.Styles(carouselElement);
} else {
carouselElement = $(this.options.carouselElement).addClass('jdExtCarousel');
}
this.carouselElement = new Fx.Styles(carouselElement, {transition: Fx.Transitions.expoOut});
this.carouselElement.normalHeight = carouselElement.offsetHeight;
if (this.options.showCarouselLabel)
this.carouselLabel = new Element('p').addClass('label').injectInside(carouselElement);
carouselWrapper = new Element('div').addClass('carouselWrapper').injectInside(carouselElement);
this.carouselWrapper = new Fx.Styles(carouselWrapper, {transition: Fx.Transitions.expoOut});
this.carouselWrapper.normalHeight = carouselWrapper.offsetHeight;
this.carouselInner = new Element('div').addClass('carouselInner').injectInside(carouselWrapper);
if (this.options.activateCarouselScroller)
{
this.carouselWrapper.scroller = new Scroller(carouselWrapper, {
area: 100,
velocity: 0.2
})
this.carouselWrapper.elementScroller = new Fx.Scroll(carouselWrapper, {
duration: 400,
onStart: this.carouselWrapper.scroller.stop.bind(this.carouselWrapper.scroller),
onComplete: this.carouselWrapper.scroller.start.bind(this.carouselWrapper.scroller)
});
}
},
fillCarousel: function() {
this.constructThumbnails();
this.carouselInner.normalWidth = ((this.maxIter * (this.options.thumbWidth + this.options.thumbSpacing + 2))+this.options.thumbSpacing) + "px";
this.carouselInner.style.width = this.carouselInner.normalWidth;
},
initCarousel: function () {
this.createCarousel();
this.fillCarousel();
if (this.options.carouselPreloader)
this.preloadThumbnails();
},
flushCarousel: function() {
this.thumbnailElements.each(function(myFx) {
myFx.element.remove();
myFx = myFx.element = null;
});
this.thumbnailElements = [];
},
toggleCarousel: function() {
if (this.carouselActive)
this.hideCarousel();
else
this.showCarousel();
},
showCarousel: function () {
this.fireEvent('onShowCarousel');
this.carouselContainer.start({
'opacity': this.options.carouselMaximizedOpacity,
'top': 0
}).chain(function() {
this.carouselActive = true;
this.carouselWrapper.scroller.start();
this.fireEvent('onCarouselShown');
this.carouselContainer.options.onComplete = null;
}.bind(this));
},
hideCarousel: function () {
this.fireEvent('onHideCarousel');
var targetTop = this.options.carouselMinimizedHeight - this.carouselContainer.normalHeight;
this.carouselContainer.start({
'opacity': this.options.carouselMinimizedOpacity,
'top': targetTop
}).chain(function() {
this.carouselActive = false;
this.carouselWrapper.scroller.stop();
this.fireEvent('onCarouselHidden');
this.carouselContainer.options.onComplete = null;
}.bind(this));
},
constructThumbnails: function () {
element = this.carouselInner;
for(i=0;i<this.galleryData.length;i++)
{
var currentImg = new Fx.Style(new Element ('div').addClass("thumbnail").setStyles({
backgroundImage: "url('" + this.galleryData[i].thumbnail + "')",
backgroundPosition: "center center",
backgroundRepeat: 'no-repeat',
marginLeft: this.options.thumbSpacing + "px",
width: this.options.thumbWidth + "px",
height: this.options.thumbHeight + "px"
}).injectInside(element), "opacity", {duration: 200}).set(this.options.thumbIdleOpacity);
currentImg.element.addEvents({
'mouseover': function (myself) {
myself.clearTimer();
myself.start(0.99);
if (this.options.showCarouselLabel)
$(this.carouselLabel).setHTML('<span class="number">' + (myself.relatedImage.number + 1) + "/" + this.maxIter + ":</span> " + myself.relatedImage.title);
}.pass(currentImg, this),
'mouseout': function (myself) {
myself.clearTimer();
myself.start(this.options.thumbIdleOpacity);
}.pass(currentImg, this),
'click': function (myself) {
this.goTo(myself.relatedImage.number);
if (this.options.thumbCloseCarousel)
this.hideCarousel();
}.pass(currentImg, this)
});
currentImg.relatedImage = this.galleryData[i];
this.thumbnailElements[parseInt(i)] = currentImg;
}
},
log: function(value) {
if(console.log)
console.log(value);
},
preloadThumbnails: function() {
var thumbnails = [];
for(i=0;i<this.galleryData.length;i++)
{
thumbnails[parseInt(i)] = this.galleryData[i].thumbnail;
}
this.thumbnailPreloader = new Preloader();
this.thumbnailPreloader.addEvent('onComplete', function() {
var textShowCarousel = formatString(this.options.textShowCarousel, this.currentIter+1, this.maxIter);
this.carouselBtn.setHTML(textShowCarousel).setProperty('title', textShowCarousel);
}.bind(this));
this.thumbnailPreloader.load(thumbnails);
},
clearThumbnailsHighlights: function()
{
for(i=0;i<this.galleryData.length;i++)
{
this.thumbnailElements[i].clearTimer();
this.thumbnailElements[i].start(0.2);
}
},
changeThumbnailsSize: function(width, height)
{
for(i=0;i<this.galleryData.length;i++)
{
this.thumbnailElements[i].clearTimer();
this.thumbnailElements[i].element.setStyles({
'width': width + "px",
'height': height + "px"
});
}
},
centerCarouselOn: function(num) {
if (!this.carouselWallMode)
{
var carouselElement = this.thumbnailElements[num];
var position = carouselElement.element.offsetLeft + (carouselElement.element.offsetWidth / 2);
var carouselWidth = this.carouselWrapper.element.offsetWidth;
var carouselInnerWidth = this.carouselInner.offsetWidth;
var diffWidth = carouselWidth / 2;
var scrollPos = position-diffWidth;
this.carouselWrapper.elementScroller.scrollTo(scrollPos,0);
}
},
initInfoSlideshow: function() {
/*if (this.slideInfoZone.element)
this.slideInfoZone.element.remove();*/
this.slideInfoZone = new Fx.Styles(new Element('div').addClass('slideInfoZone').injectInside($(this.galleryElement))).set({'opacity':0});
var slideInfoZoneTitle = new Element('h2').injectInside(this.slideInfoZone.element);
var slideInfoZoneDescription = new Element('p').injectInside(this.slideInfoZone.element);
this.slideInfoZone.normalHeight = this.slideInfoZone.element.offsetHeight;
this.slideInfoZone.element.setStyle('opacity',0);
},
changeInfoSlideShow: function()
{
this.hideInfoSlideShow.delay(10, this);
this.showInfoSlideShow.delay(500, this);
},
showInfoSlideShow: function() {
this.fireEvent('onShowInfopane');
this.slideInfoZone.clearTimer();
element = this.slideInfoZone.element;
element.getElement('h2').setHTML(this.galleryData[this.currentIter].title);
element.getElement('p').setHTML(this.galleryData[this.currentIter].description);
if(this.options.slideInfoZoneSlide)
this.slideInfoZone.start({'opacity': [0, this.options.slideInfoZoneOpacity], 'height': [0, this.slideInfoZone.normalHeight]});
else
this.slideInfoZone.start({'opacity': [0, this.options.slideInfoZoneOpacity]});
if (this.options.showCarousel)
this.slideInfoZone.chain(this.centerCarouselOn.pass(this.currentIter, this));
return this.slideInfoZone;
},
hideInfoSlideShow: function() {
this.fireEvent('onHideInfopane');
this.slideInfoZone.clearTimer();
if(this.options.slideInfoZoneSlide)
this.slideInfoZone.start({'opacity': 0, 'height': 0});
else
this.slideInfoZone.start({'opacity': 0});
return this.slideInfoZone;
},
makeLink: function(num) {
this.currentLink.setProperties({
href: this.galleryData[num].link,
title: this.galleryData[num].linkTitle
})
if (!((this.options.embedLinks) && (!this.options.showArrows) && (!this.options.showCarousel)))
this.currentLink.setStyle('display', 'block');
},
clearLink: function() {
this.currentLink.setProperties({href: '', title: ''});
if (!((this.options.embedLinks) && (!this.options.showArrows) && (!this.options.showCarousel)))
this.currentLink.setStyle('display', 'none');
},
/* To change the gallery data, those two functions : */
flushGallery: function() {
this.galleryElements.each(function(myFx) {
myFx.element.remove();
myFx = myFx.element = null;
});
this.galleryElements = [];
},
changeData: function(data) {
this.galleryData = data;
this.clearTimer();
this.flushGallery();
if (this.options.showCarousel) this.flushCarousel();
this.constructElements();
if (this.options.showCarousel) this.fillCarousel();
if (this.options.showInfopane) this.hideInfoSlideShow();
this.galleryInit=1;
this.lastIter=0;
this.currentIter=0;
this.doSlideShow(1);
},
/* Plugins: HistoryManager */
initHistory: function() {
this.fireEvent('onHistoryInit');
this.historyKey = this.galleryElement.id + '-picture';
if (this.options.customHistoryKey)
this.historyKey = this.options.customHistoryKey();
this.history = HistoryManager.register(
this.historyKey,
[1],
function(values) {
if (parseInt(values[0])-1 < this.maxIter)
this.goTo(parseInt(values[0])-1);
}.bind(this),
function(values) {
return [this.historyKey, '(', values[0], ')'].join('');
}.bind(this),
this.historyKey + '\\((\\d+)\\)');
this.addEvent('onChanged', function(){
this.history.setValue(0, this.currentIter+1);
}.bind(this));
this.fireEvent('onHistoryInited');
}
};
gallery = new Class(gallery);
gallery.implement(new Events);
gallery.implement(new Options);
gallery.Transitions = new Abstract ({
fade: function(oldFx, newFx, oldPos, newPos){
oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
oldFx.options.duration = newFx.options.duration = this.options.fadeDuration;
if (newPos > oldPos) newFx.start({opacity: 1});
else
{
newFx.set({opacity: 1});
oldFx.start({opacity: 0});
}
},
crossfade: function(oldFx, newFx, oldPos, newPos){
oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
oldFx.options.duration = newFx.options.duration = this.options.fadeDuration;
newFx.start({opacity: 1});
oldFx.start({opacity: 0});
},
fadebg: function(oldFx, newFx, oldPos, newPos){
oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
oldFx.options.duration = newFx.options.duration = this.options.fadeDuration / 2;
oldFx.start({opacity: 0}).chain(newFx.start.pass([{opacity: 1}], newFx));
}
});
/* All code copyright 2007 Jonathan Schemoul */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Follows: Preloader (class)
* Simple class for preloading images with support for progress reporting
* Copyright 2007 Tomocchino.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var Preloader = new Class({
Implements: [Events, Options],
options: {
root : '',
period : 100
},
initialize: function(options){
this.setOptions(options);
},
load: function(sources) {
this.index = 0;
this.images = [];
this.sources = this.temps = sources;
this.total = this. sources.length;
this.fireEvent('onStart', [this.index, this.total]);
this.timer = this.progress.periodical(this.options.period, this);
this.sources.each(function(source, index){
this.images[index] = new Asset.image(this.options.root + source, {
'onload' : function(){ this.index++; if(this.images[index]) this.fireEvent('onLoad', [this.images[index], index, source]); }.bind(this),
'onerror' : function(){ this.index++; this.fireEvent('onError', [this.images.splice(index, 1), index, source]); }.bind(this),
'onabort' : function(){ this.index++; this.fireEvent('onError', [this.images.splice(index, 1), index, source]); }.bind(this)
});
}, this);
},
progress: function() {
this.fireEvent('onProgress', [Math.min(this.index, this.total), this.total]);
if(this.index >= this.total) this.complete();
},
complete: function(){
$clear(this.timer);
this.fireEvent('onComplete', [this.images]);
},
cancel: function(){
$clear(this.timer);
}
});
Preloader.implement(new Events, new Options);
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Follows: formatString (function)
* Original name: Yahoo.Tools.printf
* Copyright Yahoo.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function formatString() {
var num = arguments.length;
var oStr = arguments[0];
for (var i = 1; i < num; i++) {
var pattern = "\\{" + (i-1) + "\\}";
var re = new RegExp(pattern, "g");
oStr = oStr.replace(re, arguments[i]);
}
return oStr;
}
Assuming your Gallery instance variable is "myGallery"
var theGalleryElement = $('myGallery');
var myGallery = new gallery( theGalleryElement ,{... some options ...}); // from his site
theGalleryElement.addEvents({
'mouseenter':function(){
myGallery.clearTimer();
},
'mouseleave':function(){
myGallery.prepareTimer();
}
});
Related
I am using a directive to show the number count effect for my dashboard when i used the directive for the h3 i am getting the result as NaN. when i remove the directive from the h3 i am getting the correct output.
When i looked into the directive i can the the value is get from element which shows the value as NaN. can anyone tell me what is wrong in the code?
Output with directive:
<h3 animate-numbers="" class="ng-binding">NaN</h3>
Html:
<h3 animate-numbers>{{vm.dashboard.no_of_applications}}</h3>
Controller:
vm.dashboard = {
no_of_users: 0,
no_of_applications: 0,
no_of_departments: 0,
no_of_schemes: 0,
};
Directive:
'use strict';
angular.module('ss')
.directive('animateNumbers', function ($timeout, $log) {
return {
replace: false,
scope: true,
link: function (scope, element) {
var e = element[0];
$log.log('e is', e);
var refreshInterval = 30;
var duration = 1000; //milliseconds
var number = parseInt(e.innerText);
var step = 0;
var num = 0;
var steps = Math.ceil(duration / refreshInterval);
var increment = (number / steps);
var percentCompleted = 0;
var lastNumberSlowCount = 3;
if (number > lastNumberSlowCount) {
number = number - lastNumberSlowCount;
}
scope.timoutId = null;
var slowCounter = function () {
scope.timoutId = $timeout(function () {
lastNumberSlowCount --;
if (lastNumberSlowCount < 0) {
$timeout.cancel(scope.timoutId);
} else {
number++;
e.textContent = number;
slowCounter();
}
}, 500);
};
var counter = function () {
scope.timoutId = $timeout(function () {
num += increment;
percentCompleted = Math.round((num / number) * 100);
if (percentCompleted > 60 && percentCompleted < 80) {
refreshInterval = refreshInterval + 10;
} else if (percentCompleted > 90) {
refreshInterval = 200;
}
step++;
if (step >= steps) {
$timeout.cancel(scope.timoutId);
num = number;
e.textContent = number;
if (number > lastNumberSlowCount) {
slowCounter();
}
} else {
e.textContent = Math.round(num);
counter();
}
}, refreshInterval);
};
counter();
return true;
}
};
});
I have a html canvas that I draw a rect on, when I clear the canvas the screen clears but when you move the mouse the rect reappears. I stretch the rect vertically. Here is a code pen example of what is happening, you have to double click on the canvas for the rect to appear. https://codepen.io/tjquinn/pen/BYZQqo
HTML
<div id="app">
<div class="cv">
<canvas v-on:mousedown="mouseDown" v-on:mousemove="mouseMove" v-on:mouseup="mouseUp" #dblclick="dclick" id="rect" class="rect" width="150" height="700"></canvas>
<button v-on:click="clear">
Clear
</button>
</div>
</div>
JS
methods: {
checkCloseEnough: function (p1, p2) {
return Math.abs(p1 - p2) < this.closeEnough;
},
getVal: function (x) {
this.canvas2 = document.getElementById('rect');
this.ctx2 = this.canvas2.getContext('2d');
this.st = this.canvas2.height;
this.ic = (this.st / x);
},
draw: function () {
this.ctx2.fillStyle = "#222222";
this.ctx2.fillRect(this.ctx2.rect.startX, this.ctx2.rect.startY, this.ctx2.rect.w, this.ctx2.rect.h);
this.drawHandles();
},
drawHandles: function () {
this.drawCircle(this.ctx2.rect.startX + this.ctx2.rect.w/2, this.ctx2.rect.startY, this.closeEnough); //top left corner
//drawCircle(rect.startX + rect.w, rect.startY, closeEnough);
//drawCircle(rect.startX + rect.w, rect.startY + rect.h, closeEnough);
this.drawCircle(this.ctx2.rect.startX + this.ctx2.rect.w/2, this.ctx2.rect.startY + this.ctx2.rect.h, this.closeEnough);
},
drawCircle: function (x, y, radius) {
this.ctx2.fillStyle = "#FF0000";
this.ctx2.beginPath();
this.ctx2.arc(x, y, radius, 0, 2 * Math.PI);
this.ctx2.closePath();
this.ctx2.fill();
},
checkCloseEnough: function (p1, p2) {
return Math.abs(p1 - p2) < this.closeEnough;
},
mouseDown: function (event) {
this.mouseX = event.pageX - this.canvas2.offsetLeft;
this.mouseY = event.pageY - this.canvas2.offsetTop;
// if there isn't a rect yet
if (this.ctx2.rect.w === undefined) {
this.ctx2.rect.startX = this.mouseY;
this.ctx2.rect.startY = this.mouseX;
this.dragBR = true;
}
if (this.checkCloseEnough(this.mouseX, this.ctx2.rect.startX + this.ctx2.rect.w/2) && this.checkCloseEnough(this.mouseY, this.ctx2.rect.startY)) {
this.dragTL = true;
}
else if (this.checkCloseEnough(this.mouseX, this.ctx2.rect.startX + this.ctx2.rect.w/2) && this.checkCloseEnough(this.mouseY, this.ctx2.rect.startY + this.ctx2.rect.h)) {
this.dragBR = true;
}
else {
// handle not resizing
}
this.ctx2.clearRect(0, 0, this.canvas2.width, this.canvas2.height);
this.draw();
},
mouseMove: function (event) {
this.mouseX = event.pageX - this.canvas2.offsetLeft;
this.mouseY = event.pageY - this.canvas2.offsetTop;
if (this.dragTL) {
//rect.w += rect.startX - mouseX;
this.ctx2.rect.h += this.ctx2.rect.startY - this.mouseY;
//rect.startX = mouseX;
this.ctx2.rect.startY = this.mouseY;
}
else if (this.dragBR) {
//rect.w = Math.abs(rect.startX - mouseX);
this.ctx2.rect.h = Math.abs(this.ctx2.rect.startY - this.mouseY);
}
this.ctx2.clearRect(0, 0, this.canvas2.width, this.canvas2.height);
this.draw();
},
mouseUp: function () {
this.dragTL = false;
this.dragTR = false;
this.dragBL = false;
this.dragBR = false;
},
dclick: function (e) {
console.log("Fires");
e.preventDefault();
this.ctx2.rect = {
startX: 25,
startY: 100,
w: (this.canvas2.width - 50),
h: 300,
}
this.draw();
this. ln = this.lines;
this.getVal(10);
},
clear: function () {
this.cv2 = 'rect';
this.canvas2 = document.getElementById(this.cv2);
this.ctx2 = this.canvas2.getContext('2d');
console.log(this.ctx2.clearRect(0, 0, this.canvas2.width, this.canvas2.height));
console.log("Clear should run");
},
}
})
It turns out the error was in my logic that was pointed out by Kamal Singh, I needed to add clear flags to my methods so that they do not run if the screen has been cleared.
<html>
<head>
<title>Test</title>
<script src="vue.min.js"></script>
</head>
<body>
<div id="app">
<div class="cv">
<canvas style='border:1px solid;' v-on:mousedown="mouseDown" v-on:mousemove="mouseMove" v-on:mouseup="mouseUp" #dblclick="dclick" id="rect" class="rect" width="150" height="700"></canvas>
<button v-on:click="clear">
Clear
</button>
</div>
</div>
<script>
new Vue({
el: '#app',
data: function() {
return {
rect : {},
drag : false,
closeEnough : 10,
st : 0,
ic : 0,
mouseX : 0,
mouseY : 0,
dragTL : false,
dragBL : false,
dragTR : false,
dragBR : false,
cv2: '',
ln: 0,
cleared: true
}
},
mounted: function () {
this.getVal(10);
this.draw();
},
methods: {
checkCloseEnough: function (p1, p2) {
return Math.abs(p1 - p2) < this.closeEnough;
},
getVal: function (x) {
this.canvas2 = document.getElementById('rect');
this.ctx2 = this.canvas2.getContext('2d');
this.st = this.canvas2.height;
this.ic = (this.st / x);
},
draw: function () {
this.ctx2.fillStyle = "#222222";
this.ctx2.fillRect(this.ctx2.rect.startX, this.ctx2.rect.startY, this.ctx2.rect.w, this.ctx2.rect.h);
this.drawHandles();
},
drawHandles: function () {
this.drawCircle(this.ctx2.rect.startX + this.ctx2.rect.w/2, this.ctx2.rect.startY, this.closeEnough); //top left corner
//drawCircle(rect.startX + rect.w, rect.startY, closeEnough);
//drawCircle(rect.startX + rect.w, rect.startY + rect.h, closeEnough);
this.drawCircle(this.ctx2.rect.startX + this.ctx2.rect.w/2, this.ctx2.rect.startY + this.ctx2.rect.h, this.closeEnough);
},
drawCircle: function (x, y, radius) {
this.ctx2.fillStyle = "#FF0000";
this.ctx2.beginPath();
this.ctx2.arc(x, y, radius, 0, 2 * Math.PI);
this.ctx2.closePath();
this.ctx2.fill();
},
checkCloseEnough: function (p1, p2) {
return Math.abs(p1 - p2) < this.closeEnough;
},
mouseDown: function (event) {
if(this.cleared) return;
this.mouseX = event.pageX - this.canvas2.offsetLeft;
this.mouseY = event.pageY - this.canvas2.offsetTop;
// if there isn't a rect yet
if (this.ctx2.rect.w === undefined) {
this.ctx2.rect.startX = this.mouseY;
this.ctx2.rect.startY = this.mouseX;
this.dragBR = true;
}
if (this.checkCloseEnough(this.mouseX, this.ctx2.rect.startX + this.ctx2.rect.w/2) && this.checkCloseEnough(this.mouseY, this.ctx2.rect.startY)) {
this.dragTL = true;
}
else if (this.checkCloseEnough(this.mouseX, this.ctx2.rect.startX + this.ctx2.rect.w/2) && this.checkCloseEnough(this.mouseY, this.ctx2.rect.startY + this.ctx2.rect.h)) {
this.dragBR = true;
}
else {
// handle not resizing
}
Problem: I am trying to use ng-bind-html but I am getting the following errors on the console:
The following is the controller where I am calling ngSanitize:
and using the following file:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>
In my form, I do the following to use ng-bind-html. So when I try to see my results, it is still rendering the &rather then &:
<div ng-bind-html="e.Specialty"></div>
and the following is what occurs in the Specialty:
Any help would be appreciated.
#lealceldeiro: Here is the controller in which I am trying to implement your suggestion but not sure where I will add it:
(
function(){
var $scope, $location;
var indexApp = angular.module('indexApp',['ui.bootstrap', 'ngSanitize']);
indexApp.controller('IndexController',function($scope,$sce,$http,$location,anchorSmoothScroll){
$scope.Lang = 'initVal';
$scope.ShowResults = false;
$scope.ShowDesc = true;
$scope.NoResults = false;
$scope.currentPage = 1;
$scope.maxPageNumbersToShow = 10;
$scope.formModel = {};
$scope.searchMode = 0;
$scope.miles = [{'value':'5'},{'value':'10'},{'value':'15'},{'value':'20' }];
$scope.Specialties = [{'value':'Family practice'},{'value':'General practice'},{'value':'Internal medicine'},{'value':'Pediatrics'}];
$scope.Gender = [{'value':'Male'},{'value':'Female'}];
$scope.Languages = {};
$scope.Cities = {};
//$scope.lastAction = '';
$scope.searchParam = {};
$("input").removeAttr('disabled');
$scope.searchParam.Distance = $scope.miles[0];
$scope.GetCurrentZip = function (){
try{
var lon, lat;
// console.log('starting geoposition code.');
if("geolocation" in navigator){
window.navigator.geolocation.getCurrentPosition(function(pos){
lat = pos.coords.latitude.toFixed(3);
lon = pos.coords.longitude.toFixed(3);
// console.log(lat + ' ' + lon);
$http.get("/Brokers-en-us/includes/remote/ReturnCurrentZipcode.cfm?Lat=" + lat + "&Lon=" + lon)
.then(function(response){
$scope.searchParam.Zip = response.data;
})
})
}
else{ console.log('No geolocation'); }
}
catch(err) { console.log(err.message); }
}
$scope.GetCityList = function (){
try{
$http.get("/Brokers-en-us/includes/remote/ReturnCityList.cfm")
.then(function(response){
$scope.Cities = response.data.Cities;
})
}
catch(err){}
}
$scope.GetLangList = function (){
try{
$http.get("/Brokers-en-us/includes/remote/ReturnLangList.cfm")
.then(function(response){
$scope.Languages = response.data.Languages;
})
}
catch(err){}
}
$scope.SearchProvider = function(searchParam){
try{
//debugger;
$scope.searchMode = 1;
var queryString='';
if($scope.formModel && $scope.formModel !== searchParam){
$scope.resultsCount = 0;
currentPage = 1;
}
if(searchParam){
//debugger;
$scope.formModel = searchParam;
for(var param in searchParam){
if(searchParam.hasOwnProperty(param)){
var paramValue = searchParam[param].value ? searchParam[param].value : searchParam[param];
if (paramValue.length > 0)
queryString += param + '=' + paramValue + '&';
}
}
}
console.log(queryString);
queryString= '?' + queryString + 'currentpage=' + $scope.currentPage;
$http.get("/Brokers-en-us/includes/remote/ReturnProvidersList.cfm" + queryString)
.then(function(response){
$scope.providers = response.data.provider;
$scope.resultsCount = response.data.rowCount;
if (!$scope.providers){
$scope.NoResults = true;
$scope.ShowResults = false;
$scope.ShowDesc = false;
}
else{
$scope.NoResults = false;
$scope.ShowResults = true;
$scope.ShowDesc = false;
}
})
}
catch(err){ alert('No response.: ' + err.message); }
}
/*Testing purposes*/
$scope.clearTopForm = function(searchParam){
//console.log("I clicked this.")
}
/*Clears the drop downs and input fields*/
$scope.$watch('searchParam.Distance', function(newValue, oldValue) {
//debugger;
if(newValue != ''){
//$scope.lastAction = 'miles';
$scope.searchParam.City = '';
$scope.searchParam.Specialty = '';
$scope.searchParam.Gender = '';
}
});
$scope.$watch('searchParam.Zip', function(newValue, oldValue) {
if(newValue != ''){
//$scope.lastAction = 'miles';
$scope.searchParam.Gender = '';
$scope.searchParam.Specialty = '';
$scope.searchParam.City = '';
}
});
$scope.cityChange = function(){
//debugger;
if($scope.searchParam.City != ''){
//$scope.lastAction = 'city';
$scope.searchParam.Distance = '';
$scope.searchParam.Zip = '';
}
}
$scope.specialtyChange = function(){
//debugger;
if($scope.searchParam.Specialty != ''){
//$scope.lastAction = 'specialty';
$scope.searchParam.Distance = '';
$scope.searchParam.Zip = '';
}
}
$scope.genderChange = function(){
//debugger;
if($scope.searchParam.Gender != ''){
//$scope.lastAction = 'gender';
$scope.searchParam.Distance = '';
$scope.searchParam.Zip = '';
}
}
$scope.$watchGroup(['currentPage'], function(){
try{
if($scope.searchMode == 1){
$scope.SearchProvider($scope.formModel);
}
}
catch(err){}
});
$scope.GetCityList();
$scope.GetLangList();
$scope.GetCurrentZip();
$scope.gotoElement = function (eID){
//http://jsfiddle.net/brettdewoody/y65G5/
// set the location.hash to the id of
// the element you wish to scroll to.
//$location.hash('bottom');
// call $anchorScroll()
var browserWidth = screen.availWidth;
if (browserWidth < 768)
anchorSmoothScroll.scrollTo(eID);
};
});
indexApp.service('anchorSmoothScroll', function(){
this.scrollTo = function(eID) {
// This scrolling function
// is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript
var startY = currentYPosition();
var stopY = elmYPosition(eID);
var distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY); return;
}
var speed = Math.round(distance / 100);
if (speed >= 20) speed = 20;
var step = Math.round(distance / 25);
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if (stopY > startY) {
for ( var i=startY; i<stopY; i+=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY += step; if (leapY > stopY) leapY = stopY; timer++;
} return;
}
for ( var i=startY; i>stopY; i-=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
}
function currentYPosition() {
// Firefox, Chrome, Opera, Safari
if (self.pageYOffset) return self.pageYOffset;
// Internet Explorer 6 - standards mode
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
// Internet Explorer 6, 7 and 8
if (document.body.scrollTop) return document.body.scrollTop;
return 0;
}
function elmYPosition(eID) {
var elm = document.getElementById(eID);
var y = elm.offsetTop;
var node = elm;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
} return y;
}
};
});
indexApp.directive('allowPattern',[allowPatternDirective]);
indexApp.directive('popPopup',[describePopup]);
indexApp.directive('pop', function pop ($tooltip, $timeout) {
var tooltip = $tooltip('pop', 'pop', 'event');
var compile = angular.copy(tooltip.compile);
tooltip.compile = function (element, attrs) {
var first = true;
attrs.$observe('popShow', function (val) {
if (JSON.parse(!first || val || false)) {
$timeout(function(){
element.triggerHandler('event');
});
}
first = false;
});
return compile(element, attrs);
};
return tooltip;
});
indexApp.filter('PhoneNumber', function(){
return function(phoneNumber){
var dash = '-';
var openParen = '(';
var closeParen = ') ';
if(phoneNumber){
var pn = phoneNumber;
pn = [pn.slice(0, 6), dash, pn.slice(6)].join('');
pn = openParen + [pn.slice(0, 3), closeParen, pn.slice(3)].join('');
return pn;
}
return phoneNumber;
}
});
indexApp.filter('Zip', function(){
return function(zipcode){
var dash = '-';
if(zipcode && zipcode.length > 5){
var zc = zipcode;
zc = [zc.slice(0, 5), dash, zc.slice(5)].join('');
return zc;
}
return zipcode;
}
});
function allowPatternDirective(){
return{
restrict: "A",
compile: function(tElement, tAttrs){
return function(scope, element, attrs){
element.bind("keypress", function(event){
var keyCode = event.which || event.keyCode;
var keyCodeChar = String.fromCharCode(keyCode);
if(!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))){
event.preventDefault();
return false;
}
});
}
}
}
}
function describePopup(){
return {
restrict: 'EA',
replace: true,
scope: { title: '#', content: '#', placement: '#', animation: '&', isOpen: '&' },
templateUrl: 'template/popover/popover.html'
};
}
})();
(function($) {
// #todo Document this.
$.extend($,{ placeholder: {
browser_supported: function() {
return this._supported !== undefined ?
this._supported :
( this._supported = !!('placeholder' in $('<input type="text">')[0]) );
},
shim: function(opts) {
var config = {
color: '#888',
cls: 'placeholder',
selector: 'input[placeholder], textarea[placeholder]'
};
$.extend(config,opts);
return !this.browser_supported() && $(config.selector)._placeholder_shim(config);
}
}});
$.extend($.fn,{
_placeholder_shim: function(config) {
function calcPositionCss(target)
{
var op = $(target).offsetParent().offset();
var ot = $(target).offset();
return {
top: ot.top - op.top,
left: ot.left - op.left,
width: $(target).width()
};
}
function adjustToResizing(label) {
var $target = label.data('target');
if(typeof $target !== "undefined") {
label.css(calcPositionCss($target));
$(window).one("resize", function () { adjustToResizing(label); });
}
}
return this.each(function() {
var $this = $(this);
if( $this.is(':visible') ) {
if( $this.data('placeholder') ) {
var $ol = $this.data('placeholder');
$ol.css(calcPositionCss($this));
return true;
}
var possible_line_height = {};
if( !$this.is('textarea') && $this.css('height') != 'auto') {
possible_line_height = { lineHeight: $this.css('height'), whiteSpace: 'nowrap' };
}
var isBorderBox = ($this.css('box-sizing') === 'border-box');
var isTextarea = $this.is('textarea');
var ol = $('<label />')
.text($this.attr('placeholder'))
.addClass(config.cls)
.css($.extend({
position:'absolute',
display: 'inline',
'float':'none',
overflow:'hidden',
textAlign: 'left',
color: config.color,
cursor: 'text',
paddingTop: !isTextarea && isBorderBox ? '0' : $this.css('padding-top'),
paddingRight: $this.css('padding-right'),
paddingBottom: !isTextarea && isBorderBox ? '0' : $this.css('padding-bottom'),
paddingLeft: $this.css('padding-left'),
fontSize: $this.css('font-size'),
fontFamily: $this.css('font-family'),
fontStyle: $this.css('font-style'),
fontWeight: $this.css('font-weight'),
textTransform: $this.css('text-transform'),
backgroundColor: 'transparent',
zIndex: 99,
}, possible_line_height))
.css(calcPositionCss(this))
.attr('for', this.id)
.data('target',$this)
.click(function(){
if (!$(this).data('target').is(':disabled')) {
$(this).data('target').focus();
}
})
.insertBefore(this);
$this
.data('placeholder', ol)
.on('keydown', function () {
ol.hide();
})
.on('blur change', function () {
ol[$this.val().length ? 'hide' : 'show']();
})
.triggerHandler('blur');
$(window).one("resize", function () { adjustToResizing(ol); });
}
});
}
});
})(jQuery);
jQuery(document).add(window).bind('ready load', function() {
if (jQuery.placeholder) {
jQuery.placeholder.shim();
}
});
When you use ng-bind-html, AngularJS sometimes consider some contents as unsafe (as your case), so you need to use the $sce service in order to "mark" this content as safe (to be used) like this:
$sce.trustAsHtml("CLINICAL & SOCIAL"); (See demo below)
From $sanitize
The input is sanitized by parsing the HTML into tokens. All safe
tokens (from a whitelist) are then serialized back to properly escaped
html string. This means that no unsafe input can make it into the
returned string.
In this case the "unsafe" part is &
angular
.module('app', [])
.controller('ctrl', ctrl);
function ctrl($scope, $sce) {
$scope.Specialty = $sce.trustAsHtml("CLINICAL & SOCIAL");
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>
<div ng-app="app" ng-controller="ctrl">
Specialty: <span ng-bind-html="Specialty"></span>
</div>
I need some help with my code. I want to make the str sprite invisible after 10 seconds.
I'm using this link for help: http://phaser.io/examples/v2/time/basic-timed-event
var game = new Phaser.Game(500, 550, Phaser.AUTO);
//var picture;
var Pacman = function (game) {
this.map = null;
this.layer = null;
this.pacman = null;
this.safetile = 14;
this.gridsize = 16;
this.speed = 100;
this.threshold = 3;
this.turnSpeed = 200;
this.marker = new Phaser.Point();
this.turnPoint = new Phaser.Point();
this.directions = [ null, null, null, null, null ];
this.opposites = [ Phaser.NONE, Phaser.RIGHT, Phaser.LEFT, Phaser.DOWN, Phaser.UP ];
this.current = Phaser.NONE;
this.turning = Phaser.NONE;
this.score=0;
this.scoreText='';
this.bonus=0;
this.bonusText='';
};
Pacman.prototype = {
init: function () {
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
Phaser.Canvas.setImageRenderingCrisp(this.game.canvas);
this.physics.startSystem(Phaser.Physics.ARCADE);
},
preload: function () {
// We need this because the assets are on github pages
// Remove the next 2 lines if running locally
this.load.baseURL = 'https://nikosdaskalos.github.io/pacman/';
this.load.crossOrigin = 'anonymous';
this.load.image('str', 'assets/str.png');
this.load.image('dot', 'assets/dot.jpg');
this.load.image('coin', 'assets/coin.jpg');
this.load.image('tiles', 'assets/pacman-tiles.png');
this.load.spritesheet('pacman', 'assets/pacman.png');
this.load.tilemap('map', 'assets/pacman-map.json', null, Phaser.Tilemap.TILED_JSON);
// Needless to say, graphics (C)opyright Namco
},
create: function () {
this.map = this.add.tilemap('map');
this.map.addTilesetImage('pacman-tiles', 'tiles');
this.layer = this.map.createLayer('Pacman');
//picture = game.add.sprite(game.world.centerX, game.world.centerY, 'str');
//picture.anchor.setTo(0.5, 0.5);
//game.time.events.add(Phaser.Timer.SECOND * 4, fadePicture, this);
this.dots = this.add.physicsGroup();
this.map.createFromTiles(36, this.safetile, 'str', this.layer, this.dots);
this.map.createFromTiles(7, this.safetile, 'dot', this.layer, this.dots);
this.map.createFromTiles(35, this.safetile, 'coin', this.layer, this.dots);
// The dots will need to be offset by 6px to put them back in the middle of the grid
this.dots.setAll('x', 6, false, false, 1);
this.dots.setAll('y', 6, false, false, 1);
// Pacman should collide with everything except the safe tile
this.map.setCollisionByExclusion([this.safetile], true, this.layer);
// Position Pacman at grid location 14x17 (the +8 accounts for his anchor)
this.pacman = this.add.sprite((14 * 16) + 8, (17 * 16) + 8, 'pacman', 0);
this.pacman.anchor.set(0.5);
//this.pacman.animations.add('munch', [0, 1, 2, 1], 20, true);
this.physics.arcade.enable(this.pacman);
this.pacman.body.setSize(16, 16, 0, 0);
this.cursors = this.input.keyboard.createCursorKeys();
//this.pacman.play('munch');
this.move(Phaser.LEFT);
this.scoreText = game.add.text(0, 500, 'Score: 0', { fontSize: '34px Arial', fill: 'white' });
lives = game.add.group();
game.add.text(game.world.width - 340, 500, 'Lives : ', { fontSize: '34px Arial', fill: 'white' });
this.bonusText = game.add.text(360, 500, 'Bonus: 0', { fontSize: '20px Arial', fill: 'white' });
for (var i = 0; i < 3; i++)
{
var pacman = lives.create(game.world.width - 235 + (30 * i), 517, 'pacman');
pacman.anchor.setTo(0.5, 0.5);
pacman.angle = 90;
pacman.alpha = 0.4;
}
},
//function fadePicture() {
//game.add.tween(picture).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true);
//},
checkKeys: function () {
if (this.cursors.left.isDown && this.current !== Phaser.LEFT)
{
this.checkDirection(Phaser.LEFT);
}
else if (this.cursors.right.isDown && this.current !== Phaser.RIGHT)
{
this.checkDirection(Phaser.RIGHT);
}
else if (this.cursors.up.isDown && this.current !== Phaser.UP)
{
this.checkDirection(Phaser.UP);
}
else if (this.cursors.down.isDown && this.current !== Phaser.DOWN)
{
this.checkDirection(Phaser.DOWN);
}
else
{
// This forces them to hold the key down to turn the corner
this.turning = Phaser.NONE;
}
},
checkDirection: function (turnTo) {
if (this.turning === turnTo || this.directions[turnTo] === null || this.directions[turnTo].index !== this.safetile)
{
// Invalid direction if they're already set to turn that way
// Or there is no tile there, or the tile isn't index 1 (a floor tile)
return;
}
// Check if they want to turn around and can
if (this.current === this.opposites[turnTo])
{
this.move(turnTo);
}
else
{
this.turning = turnTo;
this.turnPoint.x = (this.marker.x * this.gridsize) + (this.gridsize / 2);
this.turnPoint.y = (this.marker.y * this.gridsize) + (this.gridsize / 2);
}
},
turn: function () {
var cx = Math.floor(this.pacman.x);
var cy = Math.floor(this.pacman.y);
// This needs a threshold, because at high speeds you can't turn because the coordinates skip past
if (!this.math.fuzzyEqual(cx, this.turnPoint.x, this.threshold) || !this.math.fuzzyEqual(cy, this.turnPoint.y, this.threshold))
{
return false;
}
// Grid align before turning
this.pacman.x = this.turnPoint.x;
this.pacman.y = this.turnPoint.y;
this.pacman.body.reset(this.turnPoint.x, this.turnPoint.y);
this.move(this.turning);
this.turning = Phaser.NONE;
return true;
},
move: function (direction) {
var speed = this.speed;
if (direction === Phaser.LEFT || direction === Phaser.UP)
{
speed = -speed;
}
if (direction === Phaser.LEFT || direction === Phaser.RIGHT)
{
this.pacman.body.velocity.x = speed;
}
else
{
this.pacman.body.velocity.y = speed;
}
// Reset the scale and angle (Pacman is facing to the right in the sprite sheet)
/* this.pacman.scale.x = 1;
this.pacman.angle = 0;
if (direction === Phaser.LEFT)
{
this.pacman.scale.x = -1;
}
else if (direction === Phaser.UP)
{
this.pacman.angle = 270;
}
else if (direction === Phaser.DOWN)
{
this.pacman.angle = 90;
}
this.current = direction;
},*/
this.add.tween(this.pacman).to( { angle: this.getAngle(direction) }, this.turnSpeed, "Linear", true);
this.current = direction;
},
getAngle: function (to) {
// About-face?
if (this.current === this.opposites[to])
{
return "180";
}
if ((this.current === Phaser.UP && to === Phaser.LEFT) ||
(this.current === Phaser.DOWN && to === Phaser.RIGHT) ||
(this.current === Phaser.LEFT && to === Phaser.DOWN) ||
(this.current === Phaser.RIGHT && to === Phaser.UP))
{
return "-90";
}
return "90";
},
eatDot: function (pacman, dot) {
dot.kill();
var audio = new Audio('assets/pacman_chomp.wav');
audio.play()
this.score+=10;
this.scoreText.text= 'Score: ' + this.score;
//setTimeout(audio.play(),2000);
if (this.dots.total === 0)
{
this.dots.callAll('revive');
}
},
/*function muteAudio() {
var audio = document.getElementById('audioPlayer');
if (audio.mute = false) {
document.getElementById('audioPlayer').muted = true;
}
else {
audio.mute = true
document.getElementById('audioPlayer').muted = false;
}
}*/
eatCoin: function(pacman,coin){//pente
coin.kill();
this.score+=20;
this.scoreText.text= 'Score: ' + this.score;
var audio = new Audio('assets/pacman_eatfruit.wav');
audio.play()
if(this.coins.total===0)
{
this.coins.callAll('revive');
}
},
eatStr: function(pacman,str){//pente
str.kill();
this.bonus+=100;
this.bonusText.text= 'Bonus: ' + this.bonus;
var audio = new Audio('assets/pacman_eatfruit.wav');
audio.play()
if(this.strs.total===0)
{
this.strs.callAll('revive');
}
},
update: function () {
this.physics.arcade.collide(this.pacman, this.layer);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatDot, null, this);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatCoin, null, this);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatStr, null, this);
this.marker.x = this.math.snapToFloor(Math.floor(this.pacman.x), this.gridsize) / this.gridsize;
this.marker.y = this.math.snapToFloor(Math.floor(this.pacman.y), this.gridsize) / this.gridsize;
// Update our grid sensors
this.directions[1] = this.map.getTileLeft(this.layer.index, this.marker.x, this.marker.y);
this.directions[2] = this.map.getTileRight(this.layer.index, this.marker.x, this.marker.y);
this.directions[3] = this.map.getTileAbove(this.layer.index, this.marker.x, this.marker.y);
this.directions[4] = this.map.getTileBelow(this.layer.index, this.marker.x, this.marker.y);
this.checkKeys();
if (this.turning !== Phaser.NONE)
{
this.turn();
}
}
};
game.state.add('Game', Pacman, true);
</script>
</body>
</html>
So, can anyone help me with making the str invisible after 10 seconds?
You were pretty close.
I'm going to use pacman as an example, since I'm not 100% sure how you were going to fade out the coins. When Pacman eats them?
First, you want the following fadePicture function:
fadePicture: function() {
game.add.tween(this.pacman).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true);
},
Note how that was changed from function fadePicture().
Next, in your create function you can refer to it:
this.game.time.events.add(Phaser.Timer.SECOND * 4, this.fadePicture, this);
That replaces the following:
//game.time.events.add(Phaser.Timer.SECOND * 4, fadePicture, this);
I've created a JSFiddle with the relevant changes.
If you do want your coins to fade then I would try updating fadePicture to accept a dot/str parameter and then game.add.tween on that.
What's wrong with loading this JSON?
Select a new object, set its ID, add and save it. Trying to reload the JSON object results in an empty canvas.
http://jsfiddle.net/Sugv4/14/
function loadCanvas() {
canvas.clear();
window.alert(js);
canvas.loadFromDatalessJSON(js)
canvas.renderAll();
}
Try put this in Javascript code:
var canvas;
$(function () {
canvas = window._canvas = new fabric.Canvas('c');
fabric.Labeledrect = fabric.util.createClass(fabric.Rect, {
type: 'labeledRect',
initialize: function (options) {
options || (options = {});
this.callSuper('initialize', options);
this.set('label', options.label);
this.set('id', options.id);
},
toObject: function () {
return fabric.util.object.extend(this.callSuper('toObject'), {
label: this.get('label'),
id: this.get('id')
});
},
_render: function (ctx) {
this.callSuper('_render', ctx);
ctx.font = '10px Helvetica';
ctx.fillStyle = '#333';
ctx.fillText(this.label, -this.width / 2, -this.height / 2 + 10);
ctx.fillText(this.id, -this.width / 2, -this.height / 2 + 30);
}
});
fabric.Labeledrect.fromObject = function (object, callback) {
return new fabric.Labeledrect(object);
}
fabric.Labeledrect.async = true;
});
function voegObjectToe() {
var myObjects = document.getElementById("myObjects");
var kenmerk = myObjects.options[myObjects.selectedIndex].text;
//nieuw object
var rect = new fabric.Labeledrect({
left: canvas.width / 2,
top: canvas.height / 2
});
if (kenmerk == 'Camper') {
rect.set({
width: 80,
height: 50,
fill: '#faa',
label: 'Camper',
id: document.getElementById("myObject").value
});
} else if (kenmerk == 'Caravan') {
rect.set({
width: 80,
height: 60,
fill: '#3ac',
label: 'Caravan',
id: document.getElementById("myObject").value
});
} else if (kenmerk == 'Auto') {
rect.set({
width: 70,
height: 40,
fill: '#bbb',
label: 'Auto',
id: document.getElementById("myObject").value
});
} else if (kenmerk == "Boot") {
rect.set({
width: 150,
height: 60,
fill: '#8d1',
label: 'Boot',
id: document.getElementById("myObject").value
});
}
canvas.add(rect);
rect.set({
label: kenmerk + ' ' + rect.width * 7 + ' cm',
rx: 8,
ry: 8
});
canvas.renderAll();
}
function saveCanvas() {
js = JSON.stringify(canvas.toDatalessJSON());
}
function loadCanvas() {
//window.alert(js);
canvas.clear();
canvas.loadFromDatalessJSON(js);
canvas.renderAll();
}