JavaScript - Html5 And Javascript Sounds
I have a code that will randomly select a div from a list and inside of that div i want there to be a sound file. How would I use html5 and javascript to make it so that when a user clicks a button it would play whatever sound was associated with that button?
Code: <div id="randomdiv1" class="article_example_div"> <embed src="Black Hawk Down - Music Video - Riot.mp3" width=25 height=25 autostart=false repeat=true loop=true></embed> </div> Similar TutorialsHi, I need some help with playing sounds with javascript. What I need: When the user clicks the button it will run the function and play a sound either from the source or embedded into the website(which ever way works). Thanks alot! Hello, I am coding a slider for my portfolio which has divs that slide when you click either the arrow keys or the numbers below the slider's frame. I just can't figure out how to change the javascript/css file so that the current slide number, (the little numbers below the image), becomes a different color when you actively view it, so that it indicates to users number they're currently on. Thanks for help! Here's a draft of what it looks like so far in the front end with my grids still in place: HTML file: Code: <div id="slider" class="span-24 last"> <div id="slide2Left"> ←</div> <div id="slideFrame"> <div id="slideBoard"> <!-- the slides --> <div class="slidePoint"> Slide 1 Goes Here </div> <div class="slidePoint"> Slide 2 Goes Here </div> <div class="slidePoint"> Slide 3 Goes Here </div> <!-- end slideBoard --> </div> <div id="slideReference"></div> <!-- end slideFrame --> </div> <div id="slide2Right" class="last"> →</div> <!-- end slider section --> </div> Javascript code Code: // JavaScript Document $(document).ready(function(){ var slideTime = 700; var currentSlide = 1; var totalSlides = $("#slideBoard > div").size(); var slideWidth = $('#slideFrame').css('width'); var slideAmount = parseInt(slideWidth); function slideLeft(){ if(currentSlide > 1){ $("#slideBoard").animate({ left: ['+='+slideAmount, 'swing'] }, slideTime ); currentSlide += -1; } } function slideRight(){ if(currentSlide < totalSlides){ $("#slideBoard").animate({ left: ['+=-'+slideAmount, 'swing'] }, slideTime ); currentSlide += 1; } } function slideTo(slideNumber){ ///* slideNumber = parseInt(slideNumber); slidePos = slideNumber -1; var p1 = $('#slideBoard'); var position1 = p1.position(); var p2 = $('#slideBoard div:nth-child(' + slideNumber + ')'); //alert(p2.html()); var position2 = p2.position(); var slideFor = (-position1.left) - position2.left; //alert('p1: '+ position1.left + ' p2: '+ position2.left + ' Sliding: '+slideFor); $("#slideBoard").animate({ left: ['+='+slideFor, 'swing'] }, slideTime ); currentSlide = slideNumber; //*/ } $('#slide2Left').click(function(){ slideLeft(); }); $('#slide2Right').click(function(){ slideRight(); }); $(document).keydown(function(e){ if(e.keyCode == 37){ //alert( "left pressed" ); slideLeft(); return false; } if(e.keyCode == 39){ //alert( "rigt pressed" ); slideRight(); return false; } }); //# Slide Reference Tool for(i = 1; i < (totalSlides+1); i++){ $('#slideReference').append('<div class="slideNumber">'+i+'</div>'); } $('.slideNumber').click(function(){ slideTo($(this).html()); }); $(".slidePoint").touchwipe({ wipeLeft: function() { slideRight(); }, wipeRight: function() { slideLeft(); }, min_move_x: 20, preventDefaultEvents: true }); }); CSS Code Code: /* CSS Document */ #slider { position: relative; margin: 79px 0 50px 0; height: 500px; padding-bottom: 50px; border-bottom: 1px solid #9B9B9B; } #slideFrame { width:870px; left: 40px; min-height:460px; height:460px; overflow:hidden; position:relative; border:#CCC solid 0px; } #test { width:30px; min-height:460px; height:460px; overflow:hidden; position:relative; border:#CCC solid 0px; } #slideBoard { position:absolute; top:0px; left:0px; width:3000px; min-height:400px; margin:0px; padding:0px; background: #ccc; opacity: .3; } .slidePoint { width:870px; min-height:400px; height:410px; display:inline-block; margin:0px; padding:0xp; float:left; } .slidePoint p { padding:5px; } #slide2Left, #slide2Right{ position:absolute; top: 200px; bottom: 5px; cursor:pointer; width:20px; height:20px; color:#9B9B9B; border:#9B9B9B solid 1px; border-radius: 5px; padding:3px; text-align:center; display: inline-block; } #slide2Right{ left: 920px; } #slideReference { position:absolute; width: 770px; min-height:10px; bottom:5px; left:50px; text-align:center; } .slideNumber { border-radius: 2px; background:#929292; color:#ffffff; cursor:pointer; display:inline-block; padding:3px; margin:3px; text-align:center; min-height:15px; min-width:15px; } I am new to javascript (I started learning it today) so please explain it for newbies. I am trying to get the amount of video (in seconds) buffered already by the client and the whole duration of the video. Then, I divide them to get the precentage which was buffered so far. I have no problem storing the durating using: Code: var duration = document.getElementById('vid').duration - returns "12.6" (seconds) I am struggling with getting the buffered time. I tried: Code: var buffered = document.getElementById('vid').buffered This one returns "[object TimeRanges]". From what I understood this is some kind of an object (Like an array?). I tried returning "buffered.length" and I get "1" back. Please explain how I can do this. thanks Hi there, I am just writing to see if I can receive some help regarding an issue I'm having? I have written this application: http://bit.ly/dOHwhp - It allows the user to make melodies and change the speed of playback. It uses HTML5 and JavaScript. What I'd really like to do is have the ability for the user to save the melody in some respect. At the moment, I am using a parse harsh method. I thought potentially the user could save the #... and then load it from the URL. I have a method of loading it from the URL but no current way of 'saving' it and loading the saved version, as such. I have a feeling it would be far more advanced but, I would love to have a download feature like they have on this site: http://patternsketch.com/ Could anyone help out? This is my JavaScript file as it stands (although all files can be discovered in the source code of the page) Code: // ===== VARIABLES ===== var isPlaying = false; var curNote = 0; var curTempo = 100; // ===== FUNCTIONS ===== // playTune: Play the next note! function playTune() { if (isPlaying !== false) { var nextNote = 60000 / curTempo / 4; // Turn off all lights on the tracker's row $("#tracker li.track").removeClass("active"); // Light up the tracker on the current track $("#tracker li.track.col_" + curNote).addClass("active"); // Find each active note, play it var tmpAudio; $(".playBar[id^=control] li.track.active.col_" + curNote).each(function(i){ tmpAudio = document.getElementById($(this).data('sound_id')); if (!tmpAudio.paused) { // Pause and reset it tmpAudio.pause(); tmpAudio.currentTime = 0.0; } tmpAudio.play(); }); // Move the track forward curNote = (curNote + 1) % 16; } // if (isPlaying) } // playTune // Make a new hash function buildHash() { // Start it var newhash = ''; // For each track, check and add in a 0/1 as appropriate $(".playBar[id^=control] li.track").each(function(i){ newhash += $(this).is('.active') ? '1' : '0'; }); // Separate it newhash += '|'; // Now, toss in the note newhash += $('#temposlider').slider('value'); // Check and see if we really need to update if (location.hash != '#' + newhash) location.hash = newhash; } // buildHash // Read in our hash function parseHash() { if (location.hash.length > 0) { // Split it up, work it out, removing the actual hashmark var pieces = location.hash.substring(1).split('|'); // Set the lights var lights = pieces[0]; $(".playBar[id^=control] li.track").each(function(i){ // Make sure we haven't exceeded if (i >= lights.length) return false; // Check our location, turn on class if need be if (lights.charAt(i) == '1') { $(this).addClass('active'); } }); // Set the tempo if (typeof pieces[1] !== 'undefined') { $('#temposlider').slider('value', parseInt(pieces[1])); $('#tempovalue').innerHTML = pieces[1]; curTempo = parseInt(pieces[1]); } } } // parseHash // Clear it! function clearAll() { $(".playBar[id^=control] li.active").removeClass('active'); } // Run on DOM ready $(document).ready(function(){ // Process each of the audio items, creating a playlist sort of setup $("audio").each(function(i){ // Make a self reference for ease of use in click events var self = this; // Make a sub-list for our control var $ul = $('<ul id="control_' + this.id + '" class="playBar">'); $ul.append('<li class="header">' + this.title + '</li>'); // Add 16 list items! for (j = 0; j < 16; j++) { var $li = $('<li class="track col_'+j+'">'+self.id+'</li>') .click(function(){ $(this).toggleClass('active'); buildHash(); }) .data('sound_id', self.id); $ul.append($li); } // for (i = 0; i < 16; i++) // Append it up $('<li>').append($ul).appendTo('#lights'); }); // Bind up a click for our button $("#soundstart").click(function(){ if (isPlaying === false) { // Start the playing! curNote = 0; isPlaying = setInterval(playTune, 60000 / curTempo / 4); // Change our display this.innerHTML = "Stop"; } else { clearInterval(isPlaying); isPlaying = false; $("#tracker li.track").removeClass("active"); $("audio").each(function(){ this.pause(); this.currentTime = 0.0; }); this.innerHTML = "Play"; } }); $('#clearall').click(clearAll); $('#reload').click(parseHash); // ===== Misc ===== // Build or read the hash if (location.hash == '') { // I was building this at load - but now, no, just to be safe //buildHash(); } else { parseHash(); } // Show our value, now that we've built off of the hash $('#tempovalue').html(curTempo); // Make our tempo slider $('#temposlider').slider({ 'value': curTempo, 'min': 30, 'max': 170, 'step': 2, 'slide': function(e, ui) { curTempo = ui.value; $('#tempovalue').html(curTempo); if (isPlaying !== false) { clearInterval(isPlaying); isPlaying = setInterval(playTune, 60000 / curTempo / 4); } }, 'stop': function(e, ui) { buildHash(); } }); }); Sorry if this is the wrong forum for this question. I get confused about what forum to post a question in with regards to DHTML technologies since they are all frequently used together. Anyhoo, heres my question. I've recently discovered an interesting behavior. When I mouse over a nested element it triggers the 'onmouseout' event handler of the parent element. Take the following code snippet, for instance: Code: <table> <tr> <td onmouseout="window.alert('you moused out of td');"> <img src="image0.gif" style="height:50px; width:50px;" /> </td> </tr> </table> In the code snippet above, the 'onmouseout' event handler executes when you mouse over the image nested inside the <td> element. I wouldn't have thought this would be the appropriate behavior since from my perspective the mouse is still inside the <td> element. Can someone make comments on this. Thank You. Edit: I've discovered that mousing over a nested element causes both an 'onmouseout' and an 'onmouseover' event for the parent element. They are called back to back. Seems a little bit of an odd sequence of events but maybe it makes sense in the grand scheme of things. Yeah, right. I can play a sound on my local machine using the following code, but when I upload to a server the same code it does not play. I cannot work out why, the link below gives the code. The multi channel code is he http://www.storiesinflight.com/html5/audio.html I installed Firebug and insepcted the Net components and can see that the .wav files are being sought out but returning a 404 error. This would be fine, however the path being sought is correct. Clicking link does'nt play the sound, but removing the file and paring back to the directory brings you to the directory on the server and clicking the file does play the sound. The code works locally, and I simply cannot see what could be causing the issue in the server versions on both Firefox and Chrome. How could I make it so that instead of seeing a embed object you would just see a input button that says play. I do not need my users to be able to pause them. I really didn't know where to start with the javascript but i do have the html5 Code: <audio controls="controls"> <source src="BlackHawkDown-MusicVideo-Frontline.wav" type="audio/wav" /> <source src="BlackHawkDown-MusicVideo-Frontline.mp3" type="audio/mpeg" /> Your browser does not support the audio element. </audio> THANKS!!!! On all my html 5 pages of http://www.countyfairgrounds.net I have a drop down javascript menu for selecting a state. The thing has worked for years fine. However in switching to html5 the validator will not validate it. The are saying the option tag is obsolete. First I don't java, I do html5 and css3 currently. Ca anyonepoint me to a script dropdown that I can cut and paste - that will validate?
Hi everyone, I am trying to make an image mask using javascript. The basic idea is that the image on the canvas will appear as a black box. When the user hovers over the image a small part of it is revealed. I have attached a picture as an example because its quite hard to explain! Any help would be appreciated! Thanks, Luke How to make request "rtsp://localhost:554/sample_100kbit.mp4"? (in HTML5 or Javascript) I want to access video streaming data which source is present on Darwin server
I need to be able to drag an image from one browser window to a form text input in a different window, populating it with the image file name. I can do this easily, except that the result is the whole url, and I only want the filename to be inserted. In other words, it inserts http://www.path/path/file.jpg, but I just want to end up with file.jpg. I believe the file object .name property holds the info I need, but I don't know how to populate the input field with it. Any help appreciated. Hi, At a certain moment, a page gives a sound of falling coins. The way it is done at the moment, is by using the html object tag and javascript combination. The first time in one pageload, the moment the sound is heard, the page goes down a height of a <div>. The second time the special effects are heard, this does not happen. Ok, it is solved by playing a 'mute' sound at the onload. But most of the browsers ask, if the user allows to install a plug-in for the sound, and then asks again if the user really allows the installation. 1. Is there a way, to hear the sound without any plug-ins? 2. Is there a way to activate the sound so that the page does not roll down one forth of a inch at the first time the sound is heard, unless playing a 'mute' sound? 3. The current method works, but not in Opera browser. In fact non of the 'w3schools' html sound examples work in Opera, unless a small player is included and the user clicks the 'play'. How to make this, or a better solution to work in Opera? 4. The crazy part is, that the javascript needs to be in <body> section with the current solution to work. I wish a method where the javascript is placed in the <head> section. Here is quite a few Qs, but the idea is, that there can be a solution which solves all or most of them at ones Thanks. Code: <html> <head></head> <body> <span id="sound_element"></span> <script type="text/javascript"> document.getElementById("sound_element").innerHTML="<object height='0px' width='0px' data='"+"sounds/win.mp3"+"' ></object>"; </script> </body> </html> Hi Guys, I'm creating what is hoped to be a fun and slightly different page for Christmas. I am looking to have about 6 'dangling' objects, each that bounce on rollover (currently working) and that play a different note/tune. At the moment you will see in the code that I am using HTML5 to do this - whilst I am ok with this (I will create a flash fall back) I am unable to work out how to play a different sound for each rollover. Of course if there is a more cross browser friendly solution I'm all ears... Any help much appreciated! Please see below code... Quote: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> <script> // Mouseover/ Click sound effect- by JavaScript Kit (www.javascriptkit.com) // Visit JavaScript Kit at http://www.javascriptkit.com/ for full source code //** Usage: Instantiate script by calling: var uniquevar=createsoundbite("soundfile1", "fallbackfile2", "fallebacksound3", etc) //** Call: uniquevar.playclip() to play sound var html5_audiotypes={ //define list of audio file extensions and their associated audio types. Add to it if your specified audio file isn't on this list: "mp3": "audio/mpeg", "mp4": "audio/mp4", "ogg": "audio/ogg", "wav": "audio/wav" } function createsoundbite(sound){ var html5audio=document.createElement('audio') if (html5audio.canPlayType){ //check support for HTML5 audio for (var i=0; i<arguments.length; i++){ var sourceel=document.createElement('source') sourceel.setAttribute('src', arguments[i]) if (arguments[i].match(/\.(\w+)$/i)) sourceel.setAttribute('type', html5_audiotypes[RegExp.$1]) html5audio.appendChild(sourceel) } html5audio.load() html5audio.playclip=function(){ html5audio.pause() html5audio.currentTime=0 html5audio.play() } return html5audio } else{ return {playclip:function(){throw new Error("Your browser doesn't support HTML5 audio unfortunately")}} } } //Initialize two sound clips with 1 fallback file each: var mouseoversound=createsoundbite("whistle.ogg", "whistle.mp3") </script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script> <style type="text/css"> body { background-color: #FFF; } div { padding:0px; width:116px; height:211px; text-align:center; float:left; display:block; } </style> </head> <body> <div id="bouncy1"> <a href="#" onmouseover="mouseoversound.playclip()"><img src="creation_logo.gif" width="116" height="211" border="0" /></a></div> <div id="bouncy2"> <a href="#" onmouseover="mouseoversound.playclip()"><img src="creation_logo.gif" width="116" height="211" border="0" /></a></div> <SCRIPT> $(function(){ //Add bounce effect on Click of the DIV $('#bouncy1').mouseenter(function () { $(this).effect("bounce", { times:3 }, 500); }); $('#bouncy2').mouseenter(function () { $(this).effect("bounce", { times:3 }, 300); }); }); </SCRIPT> </body> </html> I want to know how to move a character on the path when you click the left or right arrow, but also when the left arrow is clicked it will switch between 4 images, making it look as though the characters is actually walking left arrow = moves character to left on the path(walks to the left) right arrow = moves character to right on the path(walks to the right) up arrow = character jumps This is my original code, it draws a path something like this \____ ........................................................................................\ Code: function drawMap(){ // get the canvas element using the DOM var canvas = document.getElementById('map'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext){ // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); // Stroked Path ctx.beginPath(); ctx.moveTo(0,70); ctx.lineTo(45,115); ctx.lineTo(250,115); ctx.lineTo(300,135); ctx.stroke(); ctx.closePath(); } else { alert('Your broswer does not support Canvas, We recommend getting the latest version of google chrome for the best quality'); } } Can anyone point me in the right direction? I'm keen to know what you guys think of this. In order to have HTML5 semantics and support for older browsers without Javascript enable I've written a little script that changes classes into node. For example <div class="nav"> would become <nav class="nav"> Code: //Adapt page to HTML5 function changeNodeName(element, newNodeName) { var oldNode = element, newNode = document.createElement(newNodeName), node, nextNode; node = oldNode.firstChild; while (node) { nextNode = node.nextSibling; newNode.appendChild(node); node = nextNode; } for (var i = 0; i < oldNode.attributes.length; i++) { newNode.setAttribute(oldNode.attributes[i].name, oldNode.attributes[i].value); } oldNode.parentNode.replaceChild(newNode, oldNode); } try { var theBody = document.getElementsByTagName("body")[0]; var classNames = ["article", "aside", "command", "details", "summary", "figure", "figcaption", "footer", "header", "mark", "meter", "nav", "progress", "ruby", "rt", "rp", "section", "time", "wbr"]; for (var i = 0; i < classNames.length; i++) { htmlFourElements = document.getElementsByClassName(classNames[i], theBody); for (var ii = 0; ii < htmlFourElements.length; ii++) { changeNodeName(htmlFourElements[ii], classNames[i]); } } } catch(e) { console.error(e.message); } Let me know what you think I want to have an example on web storage. I have an index.html page. On this page, there is a button which will go to another page, that is page1.html. On this page now, there is another button which will go to page2.html if clicked. Index.html > page1.html > page2.html Suppose if a user has already visited page2.html on the first time, how to make him/her goes directly on page2.html after clicking the button on index.html? The user must not again go to page1.html to get page2.html because he/she has already done that. I want to know how to store page sessions with HTML5 so that the user gets on his/her last visited page when he/she clicks the button. Thank. I followed a tutorial on Lynda for a simple HTML5 slideshow and altered it so that it doesn't auto play and has next and previous button controls. I can't quite figure out the previous button. Code: </script> <script type="text/javascript"> var imagePaths = [ "images/Test-1.jpg", "images/Test-2.jpg", "images/Test-3.jpg", "images/Test-4.jpg" ]; var showCanvas = null; var showCanvasCtx = null; var img = document.createElement("img"); var currentImage = 1; window.onload = function () { showCanvas = document.getElementById('showCanvas'); showCanvasCtx = showCanvas.getContext('2d'); img.setAttribute('width','480'); img.setAttribute('height','360'); } function nextImage() { img.setAttribute('src',imagePaths[currentImage++]); img.onload = function() { if (currentImage >= imagePaths.length) currentImage = 0; showCanvasCtx.drawImage(img,0,0,480,360); } } function prevImage() { img.setAttribute('src',imagePaths[currentImage--]); img.onload = function() { if (currentImage > imagePaths.length) currentImage = 0; showCanvasCtx.drawImage(img,0,0,480,360); } } </script> </head> <body > <br /> <div id="slideArea"> <div id="right"><input id="nxtBtn" value="Next" type="button" onclick="nextImage()"></div> <div id="left"> <input id="bkBtn"value="Back" type="button" onclick="prevImage()"></div> <div id="center"> <center> <canvas id="showCanvas" width="480" height="360" > Your browser does not support the canvas tag. <br /> Please upgrade your browser <br /><br /> <a href="#" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Firefox','','../../_images/Logo-FirefoxB.png',1)"><img src="../../_images/Logo-Firefox.png" name="Firefox" width="50" height="50" border="0"></a> <a href="https://www.google.com/chrome" target="_blank" onmouseover="MM_swapImage('Chrome','','../../_images/Logo-ChromeB.png',1)" onmouseout="MM_swapImgRestore()"><img src="../../_images/Logo-Chrome.png" name="Chrome" width="50" height="50" border="0" id="Chrome" /></a> <a href="http://www.apple.com/safari/" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Safari','','../../_images/Logo-SafariB.png',1)"><img src="../../_images/Logo-Safari.png" name="Safari" width="50" height="50" border="0" id="Safari" /></a> <a href="http://windows.microsoft.com/en-US/internet-explorer/downloads/ie" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('IE','','../../_images/Logo-IEB.png',1)"><img src="../../_images/Logo-IE.png" name="IE" width="50" height="50" border="0" id="IE" /></a> <a href="http://www.opera.com/" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Opera','','../../_images/Logo-OperaB.png',1)"><img src="../../_images/Logo-Opera.png" name="Opera" width="50" height="50" border="0" id="Opera" /></a> </canvas> </center> This doesn't quite work. If you click on the back button it goes forward one slide then back Then when you click the next button you have to click it several times before it will go forward again. Any help would be greatly appreciated I run Windows 7 and IE9, and I believe IE9 supports HTML5 Local Storage. But when I run this offline (locally) in IE9 Code: <script type="text/javascript"> function testSupport() { if (localStorage) {return "Local Storage: Supported"} else { return "Local Storage: NOT supported"; } } alert ( testSupport() ); </script> I get "LocalStorage: NOT supported". Chrome returns "Local Storage: Supported" My DOCTYPE is <!DOCTYPE html> Other tests also fail in IE. Example: Code: localStorage.setItem("name", "Hello World!"); alert(localStorage.getItem("name")); Above works in Chrome. Any advice, please? Have I not configured IE9 properly? I found a tutorial to create the HTML5 flip book. I combined three Edge "projects" with the HTML5 flip book. http://www.schrene.web44.net/Easter-2012/Book-A.html I tried to adjust the z-index so that the butterfly would fly out of the book but nothing I tried worked.. Also I wanted the animations to start with each flip of the page... I tried but I don't know enough javaScript to figure it out.... So I created a "cheesy" work around... A very large div on the right side of the page that has the animations in a mouse out event. Here is the page flip js: Code: (function() { // Dimensions of the whole book var BOOK_WIDTH = 880; var BOOK_HEIGHT = 460; // Dimensions of one page in the book var PAGE_WIDTH = 428; var PAGE_HEIGHT = 450; // Vertical spacing between the top edge of the book and the papers var PAGE_Y = ( BOOK_HEIGHT - PAGE_HEIGHT ) / 2; // The canvas size equals to the book dimensions + this padding var CANVAS_PADDING = 30; var page = 0; var canvas = document.getElementById( "pageflip-canvas" ); var context = canvas.getContext( "2d" ); var mouse = { x: 0, y: 0 }; var flips = []; var book = document.getElementById( "book" ); // List of all the page elements in the DOM var pages = book.getElementsByTagName( "section" ); // Organize the depth of our pages and create the flip definitions for( var i = 0, len = pages.length; i < len; i++ ) { pages[i].style.zIndex = len - i; flips.push( { // Current progress of the flip (left -1 to right +1) progress: 1, // The target value towards which progress is always moving target: 1, // The page DOM element related to this flip page: pages[i], // True while the page is being dragged dragging: false } ); } // Resize the canvas to match the book size canvas.width = BOOK_WIDTH + ( CANVAS_PADDING * 2 ); canvas.height = BOOK_HEIGHT + ( CANVAS_PADDING * 2 ); // Offset the canvas so that it's padding is evenly spread around the book canvas.style.top = -CANVAS_PADDING + "px"; canvas.style.left = -CANVAS_PADDING + "px"; // Render the page flip 60 times a second setInterval( render, 1000 / 60 ); document.addEventListener( "mousemove", mouseMoveHandler, true ); document.addEventListener( "mousedown", mouseDownHandler, true ); document.addEventListener( "mouseup", mouseUpHandler, false ); function mouseMoveHandler( event ) { // Offset mouse position so that the top of the spine is 0,0 mouse.x = event.clientX - book.offsetLeft - ( BOOK_WIDTH / 2 ); mouse.y = event.clientY - book.offsetTop; } function mouseDownHandler( event ) { // Make sure the mouse pointer is inside of the book if (Math.abs(mouse.x) < PAGE_WIDTH) { if (mouse.x < 0 && (page - 1) >= 0) { // We are on the left side, drag the previous page flips[page - 1].dragging = true; selPage=page-1; } else if (mouse.x > 0 && (page + 1) < flips.length) { // We are on the right side, drag the current page flips[page].dragging = true; selPage=page; } } // Prevents the text selection event.preventDefault(); } function mouseUpHandler( event ) { for( var i = 0; i < flips.length; i++ ) { // If this flip was being dragged, animate to its destination if( flips[i].dragging ) { // Figure out which page we should navigate to if( mouse.x < 0 ) { flips[i].target = -1; if (selPage == page) page = Math.min( page + 1, flips.length ); } else { flips[i].target = 1; if (selPage != page ) page = Math.max( page - 1, 0 ); } } flips[i].dragging = false; } } function render() { context.clearRect( 0, 0, canvas.width, canvas.height ); for (var i = 0; i < flips.length; i++) { var flip = flips[i]; if( flip.dragging ) { flip.target = Math.max( Math.min( mouse.x / PAGE_WIDTH, 1 ), -1 ); } flip.progress += ( flip.target - flip.progress ) * 0.2; // If the flip is being dragged or is somewhere in the middle of the book, render it if( flip.dragging || Math.abs( flip.progress ) < 0.997 ) { drawFlip( flip ); } } } function drawFlip( flip ) { // Strength of the fold is strongest in the middle of the book var strength = 1 - Math.abs( flip.progress ); if (strength < 0.01) strength=0.01; // Width of the folded paper var foldWidth = ( PAGE_WIDTH * 0.5 ) * ( 1 - flip.progress ); // X position of the folded paper var foldX = PAGE_WIDTH * flip.progress + foldWidth; // How far the page should outdent vertically due to perspective var verticalOutdent = 20 * strength; // The maximum width of the left and right side shadows var paperShadowWidth = ( PAGE_WIDTH ) * Math.max( Math.min( 1 - flip.progress, 0.5 ), 0 ); var rightShadowWidth = ( PAGE_WIDTH ) * Math.max( Math.min( strength, 0.5 ), 0 ); var leftShadowWidth = ( PAGE_WIDTH ) * Math.max( Math.min( strength, 0.5 ), 0 ); // Change page element width to match the x position of the fold flip.page.style.width = Math.max(foldX, 0) + "px"; context.save(); context.translate( CANVAS_PADDING + ( BOOK_WIDTH / 2 ), PAGE_Y + CANVAS_PADDING ); // Draw a sharp shadow on the left side of the page context.strokeStyle = 'rgba(0,0,0,'+(0.05 * strength)+')'; context.lineWidth = 30 * strength; context.beginPath(); context.moveTo(foldX - foldWidth, -verticalOutdent * 0.5); context.lineTo(foldX - foldWidth, PAGE_HEIGHT + (verticalOutdent * 0.5)); context.stroke(); // Right side drop shadow var rightShadowGradient = context.createLinearGradient(foldX, 0, foldX + rightShadowWidth, 0); rightShadowGradient.addColorStop(0, 'rgba(0,0,0,'+(strength*0.2)+')'); rightShadowGradient.addColorStop(0.8, 'rgba(0,0,0,0.0)'); context.fillStyle = rightShadowGradient; context.beginPath(); context.moveTo(foldX, 0); context.lineTo(foldX + rightShadowWidth, 0); context.lineTo(foldX + rightShadowWidth, PAGE_HEIGHT); context.lineTo(foldX, PAGE_HEIGHT); context.fill(); // Left side drop shadow var leftShadowGradient = context.createLinearGradient(foldX - foldWidth - leftShadowWidth, 0, foldX - foldWidth, 0); leftShadowGradient.addColorStop(0, 'rgba(0,0,0,0.0)'); leftShadowGradient.addColorStop(1, 'rgba(0,0,0,'+(strength*0.15)+')'); context.fillStyle = leftShadowGradient; context.beginPath(); context.moveTo(foldX - foldWidth - leftShadowWidth, 0); context.lineTo(foldX - foldWidth, 0); context.lineTo(foldX - foldWidth, PAGE_HEIGHT); context.lineTo(foldX - foldWidth - leftShadowWidth, PAGE_HEIGHT); context.fill(); // Gradient applied to the folded paper (highlights & shadows) var foldGradient = context.createLinearGradient(foldX - paperShadowWidth, 0, foldX, 0); foldGradient.addColorStop(0.35, '#fafafa'); foldGradient.addColorStop(0.73, '#eeeeee'); foldGradient.addColorStop(0.9, '#fafafa'); foldGradient.addColorStop(1.0, '#e2e2e2'); context.fillStyle = foldGradient; context.strokeStyle = 'rgba(0,0,0,0.06)'; context.lineWidth = 0.5; // Draw the folded piece of paper context.beginPath(); context.moveTo(foldX, 0); context.lineTo(foldX, PAGE_HEIGHT); context.quadraticCurveTo(foldX, PAGE_HEIGHT + (verticalOutdent * 2), foldX - foldWidth, PAGE_HEIGHT + verticalOutdent); context.lineTo(foldX - foldWidth, -verticalOutdent); context.quadraticCurveTo(foldX, -verticalOutdent * 2, foldX, 0); context.fill(); context.stroke(); context.restore(); } })(); Here is the js for activating the Edge animations: Code: <script> function playAnim1(){ var comp = $.Edge.getComposition("page1"); var stage = comp.getStage(); stage.play("play1"); } $(document).ready(function(){ setTimeout(playAnim1, 1000); }); function playAnim2(){ var comp = $.Edge.getComposition("page2"); var stage = comp.getStage(); stage.play("play2"); } $(document).ready(function(){ setTimeout(playAnim2, 1000); }); function playAnim3(){ var comp = $.Edge.getComposition("page3"); var stage = comp.getStage(); stage.play("play3"); } $(document).ready(function(){ setTimeout(playAnim3, 1000); }); </script> Not sure if the things I want to accomplish with this are even possible??? If anybody has any help or advice I would greatly appreciate it. |