JavaScript - Html5 Canvas Slideshow With Text Display
I am learning Javascript and HTML5...
I am trying to create a slideshow using canvas with text display of what the current image is. I have done this without canvas but I want to use canvas this time. My idea involves using the file name as the text display. Here is my working slideshow.. Code: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Slide Show</title> <script type="text/javascript"> function MM_swapImgRestore() { //v3.0 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; } function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } </script> <script type="text/javascript"> var imagePaths = [ "images/Summer.jpg", "images/Spring.jpg", "images/Fall.jpg", "images/Winter.jpg", "images/Puppies.jpg", "images/Duck.jpg" ]; var showCanvas = null; var showCanvasCtx = null; var img = document.createElement("img"); var currentImage = 0; window.onload = function () { showCanvas = document.getElementById('showCanvas'); showCanvasCtx = showCanvas.getContext('2d'); img.setAttribute('width','480'); img.setAttribute('height','360'); } function nextImage() { currentImage++; if (currentImage >= imagePaths.length) currentImage = 0; img.setAttribute('src',imagePaths[currentImage]); img.onload = function() { showCanvasCtx.drawImage(img,0,0,480,360); } } function prevImage() { currentImage--; if (currentImage < 0) currentImage = imagePaths.length-1; img.setAttribute('src',imagePaths[currentImage]); img.onload = function() { showCanvasCtx.drawImage(img,0,0,480,360); } } </script> <style type="text/css"> <!-- #showCanvas { background-image: url(images/Summer.jpg); } #center { height: 360px; width: 491px; float: right; } #slideArea { height: 381px; width: 600px; margin-right: auto; margin-left: auto; } #right { height: 361px; width: 52px; float: right; } #left { float: left; height: 360px; width: 52px; } #nxtBtn { width: 57px; height: 57px; position: relative; top: 120px; } #bkBtn { height: 57px; width: 57px; position: relative; top: 120px; } #displayText { width: 600px; height: 20px; float: left; text-align: center; } --> </style> </head> <body> <br /> <div id="slideArea"> <div id="right"> <a href="#" id="nxtBtn"onClick="nextImage()"onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Next','','images/arrow-right-B.png',1)"><img src="images/arrow-right-A.png" name="Next" width="51" height="75" border="0"></a> </div> <div id="left"> <a href="#" id="bkBtn" onClick="prevImage()"onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Left','','images/arrow-left-B.png',1)"><img src="images/arrow-left-A.png" name="Left" width="51" height="75" border="0"></a></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 </canvas> </center> </div> <div id="displayText">Display Text</div> </div> </body> </html> This is what I came up with so far but it doesn't work. Code: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Slide Show</title> <script type="text/javascript"> function MM_swapImgRestore() { //v3.0 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; } function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } </script> <script type="text/javascript"> ////added this code to be able to pull the display text from "imageName" var imagePath = ["images/]; var imageName = [ "Summer", "Spring", "Fall", "Winter", "Puppies", "Duck" ]; var imagePaths = imagePath + imageName + ".jpg"; ///////////////////// var showCanvas = null; var showCanvasCtx = null; var img = document.createElement("img"); var currentImage = 0; window.onload = function () { showCanvas = document.getElementById('showCanvas'); showCanvasCtx = showCanvas.getContext('2d'); img.setAttribute('width','480'); img.setAttribute('height','360'); } function nextImage() { currentImage++; if (currentImage >= imagePaths.length) currentImage = 0; img.setAttribute('src',imagePaths[currentImage]); img.onload = function() { showCanvasCtx.drawImage(img,0,0,480,360); } } function prevImage() { currentImage--; if (currentImage < 0) currentImage = imagePaths.length-1; img.setAttribute('src',imagePaths[currentImage]); img.onload = function() { showCanvasCtx.drawImage(img,0,0,480,360); } } </script> <style type="text/css"> <!-- #showCanvas { background-image: url(images/Summer.jpg); } #center { height: 360px; width: 491px; float: right; } #slideArea { height: 381px; width: 600px; margin-right: auto; margin-left: auto; } #right { height: 361px; width: 52px; float: right; } #left { float: left; height: 360px; width: 52px; } #nxtBtn { width: 57px; height: 57px; position: relative; top: 120px; } #bkBtn { height: 57px; width: 57px; position: relative; top: 120px; } #displayText { width: 600px; height: 20px; float: left; text-align: center; } --> </style> </head> <body> <br /> <div id="slideArea"> <div id="right"> <a href="#" id="nxtBtn"onClick="nextImage()"onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Next','','images/arrow-right-B.png',1)"><img src="images/arrow-right-A.png" name="Next" width="51" height="75" border="0"></a> </div> <div id="left"> <a href="#" id="bkBtn" onClick="prevImage()"onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Left','','images/arrow-left-B.png',1)"><img src="images/arrow-left-A.png" name="Left" width="51" height="75" border="0"></a></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 </canvas> </center> </div> <div id="displayText">Display Text</div> </div> </body> </htm> Any help would be greatly appreciated. Similar TutorialsHi there! I found this code, in reply to someone's problem, on this forum. I have altered it to my own needs, as it's an excellent piece of code. However, I would like it to run under HTML5. I believe I need to add "canvas" code to do the same?? I have already changed the doctype! HTML heading etc., Can anyone help? Many, many thanks!! Code: <!doctype html> <head> <meta charset=UTF-8" /> <title>Crazy Rally - France</title> <script type="text/javascript"> var frames = new Array(); //load frames into array for(var i = 1; i < 417; i++){ frames[i] = new Image(480,320); frames[i].src = "track" + i + ".png"; } //playback var currentFrameNumber = 1; var fps = 30; // frames / second const speed = 1000 / fps; // milliseconds //var speed = 33; function nextFrame( ) { document.getElementById("display").src = frames[currentFrameNumber].src; currentFrameNumber = ( currentFrameNumber + 1 ) % frames.length; setTimeout( nextFrame, speed ); } window.onload = nextFrame; </script> </head> <body> <img id="display" src="track1.png" width="480" height="320"> </body> </html> I am trying to create an Asteroids type game using JavaScript along with html5's canvas element for drawing. I have searched around and have looked at examples but I can't figure out what is wrong with my rendering that I do in the game loop that is run every frame. The problem appears to be only that the canvas is not cleared at the beginning of each frame but I feel there might be something wrong also. The code used and shown below only works in Firefox but not Google Chrome or Safari. Here is a picture of what it renders in Chrome: What is is supposed to look like and is in Firefox: Here is my set up for drawing on the canvas: Code: var canvas = null; var c2d = null; //... window.onload = init; function init() { canvas = document.getElementById('canvas'); c2d = canvas.getContext('2d'); setInterval( step, 1000/FPS ); //... //c2d.setTransform(1,0,0,1,0,0); // reset to identity <--Do I need this? } Below is the game loop function. Am I clearing the canvas correctly because it does not clear the screen? Also am I using the save and restore functions correctly? Each asteroid and player drawn is at a different of position and rotation so am I doing it correct to draw them? Code: function step() { //... canvas.width = canvas.width; //clear canvas PROBLEM //Things I have tried: //canvas.height = canvas.height; //clear canvas //c2d.clearRect(0, 0, canvas.width, canvas.height); for (u=0;u<asteroids.length;u++) { c2d.save(); asteroids[u].draw(); c2d.restore(); } c2d.save(); player.draw(); c2d.restore(); c2d.strokeStyle = "#000000"; c2d.stroke(); } Below is the Asteroid and Player drawing functions. The Asteroid is a polygon and the Player is a triangle. Both rotate and are draw correctly but should I be passing a reference to the drawing reference? Code: function Asteroid_draw() { c2d.translate( this.x, this.y ); c2d.rotate(this.angle); for (i=0;i<this.points_x.length-1;i++) { c2d.moveTo(this.points_x[i],this.points_y[i]); c2d.lineTo(this.points_x[i+1],this.points_y[i+1]); } c2d.moveTo(this.points_x[0],this.points_y[0]); c2d.lineTo(this.points_x[this.points_x.length-1],this.points_y[this.points_x.length-1]); } function Player_draw() { c2d.translate( this.x, this.y ); c2d.rotate(this.angle); //Points {0,-12}{7,5}{-7,5} c2d.moveTo(0,-12); c2d.lineTo(7,5); c2d.moveTo(7,5); c2d.lineTo(-7,5); c2d.moveTo(-7,5); c2d.lineTo(0,-12); } Any help is appreciated. I'm trying to finish off a NotePad/SketchPad app using the HTML5 canvas element and i am getting an error when i try to PUT image data to the canvas. also the getImageData() function for CANVAS is also not working. I would like to get this working soon, because i have a really nice Prototype of a 7 inch Touch screen device i would like to install this to. Error: canvas.putImageData is not a function according to all of the HTML5 canvas tutorials i've read (including the one on Mozilla-Dev), it should be correct, but it's still throwing this error. It makes no sense at all. I remember getting a similar error to this before by using the DOM element identifier - getElementByID() where the "D" is a capital letter when it should have been a lower case. However that doesn't seem to be the case here. Can anyone help me out with this? here's my HTML & JS code The main HTML UI file Code: <html><head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> <title>Sketch Book v1.0</title> <script src="SketchBook.js" type="text/javascript"></script> <script src="JSxpcom.js" language="text/javascript"></script> </head> <body onLoad="Init();"> <div id="SketchPageView"> <canvas id="SketchPage" width="480" height="640" style="background: #C7C1A3; position: absolute; top: 0px; left: 0px;" onmousedown="Draw(this, event);"></canvas> </div> <div id="Options" style="position: absolute; visibility: hidden; top: 100px; left: 50px;"> <table cellwidth="100" border="0" cellpadding="0" cellspacing="0" height="50"> <tbody><tr><td><img src="./Image/TL-black.PNG" height="19" width="19"></td><td bgcolor="#bce0f8"><center><b>Options</b></center><img src="./Image/delete.png" style="position:absolute; top: 2px; left: 150px; height: 18; width: 18;" onClick="HideOptions();"></td><td><img src="./Image/TR-black.PNG" height="19" width="19"></td></tr> <tr><td bgcolor="#bce0f8"></td> <td bgcolor="#bce0f8"> <div style="border: 1px solid black;"> <table> <tbody><tr> <td><center>Pen Size</center></td><td><center>Color</center></td> </tr> <tr> <td> <select id="GetPenSize" onchange="UpdatePenSize();"> <option value="1">1 px</option> <option value="2">2 px</option> <option value="3">3 px</option> <option value="4">4 px</option> <option value="5">5 px</option> </select> </td> <td> <select id="GetPenColor" onchange="UpdatePenColor();"> <option value="Black">Black</option> <option value="White">White</option> <option value="Red">Red</option> <option value="Blue">Blue</option> <option value="Green">Green</option> <option value="Brown">Brown</option> </select> </td> </tr> <tr> <td><input value="Restore" onclick="RestoreData();" type="button"></td><td><input value="Backup" onclick="BackupData();" type="button"></td> </tr> <tr> <td><input value="Encrypt" onclick="EncryptData();" type="button"></td><td><input value="DeCrypt" onclick="DecryptData();" type="button"></td> </tr> </tbody></table> </div> </td> <td bgcolor="#bce0f8"></td></tr> <tr><td><img src="./Image/BL-black.PNG" height="19" width="19"></td> <td bgcolor="#bce0f8"></td><td align="right"><img src="./Image/BR-black.PNG" height="19" width="19"></td></tr> </tbody></table> </div> <table id="UI" style="position: absolute; top: 0px; left: 412px; visibility: visible;" border="0" cellpadding="0" cellspacing="0" width="40"> <tbody><tr><td><img src="./Image/TL-black.PNG" height="19" width="19"></td><td bgcolor="#bce0f8"></td><td><img src="./Image/TR-black.PNG" height="19" width="19"></td></tr> <tr><td bgcolor="#bce0f8"></td> <td bgcolor="#bce0f8" height="600"> <img src="./Image/up.png" style="width: 30px; height: 30px;" onclick="NextNote('up');"><br><br><br><br> <img src="./Image/plus.png" style="width: 30px; height: 30px;" onclick="NewSketch();"><br><br><br><br> <img src="./Image/save.png" style="width: 30px; height: 30px;" onclick="SaveSketch();"><br><br><br><br> <img src="./Image/clear.png" style="width: 30px; height: 30px;" onclick="ClearSketch();"><br><br><br><br> <img src="./Image/delete.png" style="width: 30px; height: 30px;" onclick="DeleteSketch();"><br><br><br><br> <img src="./Image/gear.png" style="width: 30px; height: 30px;" onclick="ShowOptions();"><br><br> <img src="./Image/down.png" style="width: 30px; height: 30px;" onclick="NextNote('down');"> </td> <td bgcolor="#bce0f8"></td> </tr> <tr><td><img src="./Image/BL-black.PNG" height="19" width="19"></td> <td bgcolor="#bce0f8"></td> <td align="right"><img src="./Image/BR-black.PNG" height="19" width="19"></td></tr> </tbody></table> </body></html> The JS file (has the CANVAS manipulation code in it) Code: var SketchDataFolder = "c:\\"; var PenSize = "3"; var PenShape = "Circle"; var PenColor = "Black"; var LoadFile = ""; var UIstatus = "visible"; var CurrentNote = 0; var BGcolor = "#C7C1A3"; var DataPath = "\Data\\"; var FileList = []; var SystemPath; var UIstatus = "visible"; var Server = "localhost"; document.onkeyup = ToggleUI; function Init() { // Get the System Path GetSystemPath("SketchBook.html"); // Load All Filenames of the DataPath directory into an array GetFileList(SystemPath + DataPath, FileList); //Load the first Note onto the canvas // if there are no notes in the directory, don't try to load anything if(FileList.length > 0) { var NxtNote = LoadFromDisk(FileList[CurrentNote]); // Load the image data onto the canvas var canvas = document.getElementById("SketchPage"); var context = canvas.getContext("2d"); canvas.putImageData(NxtNote , 0 , 0 ); } } function HideOptions() { document.getElementById("Options").style.visibility = "hidden"; } function ToggleUI(e) { var KeyID = (window.event) ? event.keyCode : e.keyCode; var KeyValue = 18; // Use a key to hide the toolbars so that most of the screen is used for the UI if(KeyID == KeyValue) { if(UIstatus == "visible") { UIstatus = "hidden"; document.getElementById("UI").style.visibility = "hidden"; return; } if(UIstatus == "hidden") { UIstatus = "visible"; document.getElementById("UI").style.visibility = "visible"; } } } function ShowOptions() { document.getElementById("Options").style.visibility = "visible"; } function UpdatePenSize() { PenSize = document.getElementById('GetPenSize').value; } function UpdatePenShape() { PenShape = document.getElementById('GetPenShape').value; } function UpdatePenColor() { PenColor = document.getElementById('GetPenColor').value; } function Draw(element, event) { document.addEventListener("mousemove", PenHandler, true); document.addEventListener("mouseup", upHandler, true); event.stopPropagation(); event.preventDefault(); function PenHandler(event) { var x = event.clientX; var y = event.clientY; // mouse event goes here var canvas = document.getElementById("SketchPage"); var ctx = canvas.getContext("2d"); if (PenShape ="Circle") { // This draws a circle ctx.fillStyle = PenColor; ctx.beginPath(); ctx.arc(x, y, PenSize, 0, Math.PI*2, true); ctx.closePath(); ctx.fill(); } event.stopPropagation(); } function upHandler(event) { document.removeEventListener("mouseup", upHandler, true); document.removeEventListener("mousemove", PenHandler, true); event.stopPropagation(); } } function SaveSketch() { // Get the current file name var FileName = SystemPath + DataPath + CurrentNote + ".img"; var canvas = document.getElementById("SketchPage"); var context = canvas.getContext("2d"); var ImgData = context.getImageData(0, 0, canvas.width, canvas.height); alert(ImgData); // Write the PNG file to the disk SaveToDisk(FileName, ImageData); } function NextNote(Direction) { if(Direction == "up") { // Display the previoius note CurrentNote--; // Make sure you don't incrimnet to a non-existant note if(CurrentNote <= 0) { CurrentNote = FileList.length; } var NxtNote = LoadFromDisk(SystemPath + DataPath + FileList[CurrentNote]); // Load the image data onto the canvas var canvas = document.getElementById("SketchPage"); var context = canvas.getContext("2d"); canvas.putImageData(NxtNote , 0 , 0 ); return; } if(Direction == "down") { //Display the Next note CurrentNote++; // Make sure you don't incrimnet to a non-existant note if(CurrentNote > FileList.length) { CurrentNote = 0; } var NxtNote = LoadFromDisk(SystemPath + DataPath + FileList[CurrentNote]); // Load the image data onto the canvas var canvas = document.getElementById("SketchPage"); var context = canvas.getContext("2d"); canvas.putImageData(NxtNote , 0 , 0 ); return; } } function DeleteNote() { // Delete The current note DeleteFile(SystemPath + DataPath + FileList[CurrentNote]); // Reload the Directory List // Re-Dim the FileList Array FileList.length = 0; GetFileList(SystemPath + DataPath, FileList); // Load The Previous Note // Display the previoius note CurrentNote--; // Make sure you don't incrimnet to a non-existant note if(CurrentNote <= 0) { CurrentNote = FileList.length; } var NxtNote = LoadFromDisk(FileList[CurrentNote]); // Load the image data onto the canvas var canvas = document.getElementById("SketchPage"); var context = canvas.getContext("2d"); canvas.putImageData(NxtNote , 0 , 0 ); return; } function AddNote() { // Add a note to the notebook and at the end of the File List // **** Later this function should be modified to be an INSERT function rather than just an add // Just incase the user needs to go back an edit and add more things to their notebook } function ClearSketch() { // Clear the contents of the Canvas //Draw a rectangle that covers the canvas var canvas = document.getElementById("SketchPage"); var ctx = canvas.getContext("2d"); ctx.fillStyle = BGcolor; ctx.fillRect (0, 0, canvas.width, canvas.height); } function Crypt(method) { // This function will Encrypt or Decrypt All the NoteData if(method == "encrypt") { return; } if(method == "decrypt") { return; } } function Archive(method) { // This function will Restore or Backup all NoteData to a network resource if(method == "restore") { return; } if(method == "backup") { return; } } // ******************** These are the XPCOM Functions ************************ function GetSystemPath(ApplicationName) { // This function should Detect the system directory of the app // and return that string as the SystemPath variable // You must supply the filename of the HTML file that it is being called from // I suppose later i could add the code to detect the HTML's actual file name // It's on the ToDo List... var GetSysPath = self.location; GetSysPath = GetSysPath + ""; Get = GetSysPath.replace("file:///" , ""); Get = Get.replace(/\//g , "\\"); Get = Get.replace(ApplicationName, ""); SystemPath = Get; return SystemPath; } function DeleteFile(FileName) { // Delete a local file netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); var aFile = Components.classes["@mozilla.org/file/local;1"].createInstance(); if (aFile instanceof Components.interfaces.nsILocalFile) { aFile.initWithPath(FileName); aFile.remove(false); } } function GetFileList(Directory, FileList) { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); var _nsILocalFile = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); // initialize path to work with _nsILocalFile.initWithPath(Directory); // get file interface implemenation // this means that an XPCOM Class can implement multiple interface var lv_oFile = _nsILocalFile.QueryInterface(Components.interfaces.nsIFile); var lv_oEntries = lv_oFile.directoryEntries; while(lv_oEntries.hasMoreElements()) { var lv_cFile = lv_oEntries.getNext() .QueryInterface(Components.interfaces.nsIFile).path; FileList.push(lv_cFile); } } function SaveToDisk(filepath, content) { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch (e) { alert("Permission to save file was denied."); } var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); file.initWithPath( filepath ); if ( file.exists() == false ) { file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 ); } var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"] .createInstance( Components.interfaces.nsIFileOutputStream ); outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 ); var output = content; var result = outputStream.write( output, output.length ); outputStream.close(); } function LoadFromDisk(filePath) { if(window.Components) try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); file.initWithPath(filePath); if (!file.exists()) return(null); var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream); inputStream.init(file, 0x01, 00004, null); var sInputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream); sInputStream.init(inputStream); return(sInputStream.read(sInputStream.available())); } catch(e) { //alert("Exception while attempting to load\n\n" + e); return(false); } return(null); } 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 Hello, I'm new here so.. hi! You'll probably be seeing me a lot. Anyways here's my questions. I am trying to get a function to draw 5 randomly sized and colored rectangles nested within each other. Meaning each rectangle should not go outside the boundaries of the rectangle it is in. The color thing I've got down in a randomColor() function. It's the nesting rectangles inside rectangles that is confusing me (hense me being up for the past 4 hours trying to understand it) I started out with very simple code just making 5 rectangles of reducing sizes nested in each other, then added the Math.random to randomize all the sizes. Now I'm at this point and have lost my way. Please help, or maybe there is just an easier way. I added a bunch of comments in my code so maybe you'll understand what I'm trying to do. Code: function rect() { // rectangle generator autoctx.clearRect(0, 0, 400, 400); // clear canvas // declare variables var x; var y; var width; var height; var i = 0; // counter // create random x,y coordinates x = Math.round(Math.random() * 100); y = Math.round(Math.random() * 100); do { // create random size rectangle width = Math.round(Math.random() * 400); height = Math.round(Math.random() * 400); } while (width < 100 || height < 100); // make sure rectangle is big enough autoctx.fillStyle = randomColor(); // Runs random color generator autoctx.fillRect(x, y, width, height); // fill first rectangle do { x += (Math.round(Math.random() * 15)); // choose new random coordinates within previous rectangle y += (Math.round(Math.random() * 15)); // choose new random coordinates within previous rectangle //*********** KEEPS RECTANGLE HEIGHT AND WIDTHS FROM BEING A NEGATIVE NUMBER ***********// do { //*** WIDTH TESTER ***// validates width to be within previous rectangles width var testW = 0; // new width tester variable testW = width - (Math.round(Math.random() * (2 * x))); // store test width if (testW > 0) { width = testW; // if test width > 0 store in width } } while (testW < 0); // if test width < 0 continue loop do { //*** HEIGHT TESTER ***// validates height to be within previous rectangles height var testH = 0; // create height testing variable testH = height - (Math.round(Math.random() * (2 * y))); // calculate new test height if (testH > 0) { // if test height is > 0 height = testH; // store as height } } while (testH < 0); // if test height < 0 try again //*** Fills final rectangle values ***// autoctx.fillStyle = randomColor(); // Runs random color generator autoctx.fillRect(x, y, width, height); i++; // add 1 to counter } while (i < 4); // kick out of loop after the 5th rectangle } thanks guys I hope I'm not too confusing or anything, any help would be greatly appreciated! 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 What I am trying to achieve is when the Input Box value is increased or decreased using the up/down arrows that the new value will be writen to the Canvas, though the code I have works it dosent render properly. I also have a Span Tag absouletly positioned within the canvas which works perfectly but I'd like the Canvas text to work instead. Not sure if it's possible. Code: <!doctype html> <html> <head> <title></title> <!------------------------------------- STYLE -------------------------------------> <style type="text/css"> canvas { background:#222; } #length{ position:absolute; left:10px; top:10px; width:150px; } #text_in_canvas{ position:absolute; left:500px; top:100px; width:400px; font-style: normal; font-size: 25px; color: red; } </style> <!------------------------------------- CODE -------------------------------------> <script type="text/javascript"> var fps = 100; function draw_canvas() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d");//returns drawing functions to allow the user to draw on the canvas. var width = canvas.scrollWidth; var height = canvas.scrollHeight; // var startPosX = (300); // Start Position from X axis var startPosY = (height - 50); // Start Position from Y axis // var length = document.getElementById("length").value; //Get's value from Text Input Box var text = "This is the number from Input Box: " + length; document.getElementById("text_in_canvas").innerHTML= text; //LEFT BLOCK context.beginPath(); context.rect(0, 0, 250, height); //position & size of left block context.fillStyle = 'black'; //background colour context.fill(); context.lineWidth = 0; context.strokeStyle = 'red'; context.stroke(); context.closePath(); //TEXT context.font = 'bold 28px sans-serif'; // set text font context.textAlign = 'center'; context.fillStyle = '#FFFFFF'; // set text color context.fillText(text, 548, 50); } </script> </head> <body onload="draw_canvas()"> <!-- CANVAS STARTS HERE --> <div id="" style="width:1000px;height:600;margin:auto;position:relative;"> <canvas id="myCanvas" width="1000" height="600" style="border:1px solid #000000;"></canvas> <!-- FORM BEGINS HERE --> <form id="my_form"> <label for="length">Outside too Outside Wallplate Measurement (millimeters):</label> <input type="number" id="length" name="length" step="1" min="0" max="" placeholder="" oninput="JavaScript: draw_canvas()"> </form> <span id="text_in_canvas"></span> <!-- FORM END's HERE --> </div> <!-- CANVAS END's HERE --> </body> </html> I am building a custom slideshow that is pulling data from an xml sheet to create each "Slide" each slide consists of several elements on the xml sheet. I have javascript currently putting together the correct information and creating a new div for each "slide". What I need is to display the first div(slide) and then hit a next button to get to display the next div(slide). Below the first set of code is a snapshot of code simply to illustrate that it is creating the correct divs. Those divs all have content in them I just took the code from firebug. Code: <!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> <body> <div id="page-wrap"> <button id="nextButton2">next('div')</button> <button id="prevButton2">prev('div')</button> <div id="start" style="background: none repeat scroll 0% 0% red;"></div> <div id="link_Babbling Brook" class="art"> <div id="link_Botany 101" class="art"> <div id="link_Cracking Up" class="art"> <div id="link_Eclipse" class="art"> <div id="link_Equinox" class="art"> <div id="link_Foliage Fluoresced" class="art"> <div id="link_In Vein" class="art"> <div id="link_Microscopic" class="art"> <div id="link_Pickup Sticks" class="art"> <div id="link_Relief" class="art"> <div id="link_Rhubarb" class="art"> <div id="link_Snow Dyed Shibori" class="art"> <div id="link_Symmetry" class="art"> <div id="link_Undulations" class="art"> <div id="link_Willow Mist" class="art"> <div id="link_Wired" class="art"> </div> </body> </html> Javascript code Code: if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } $(document).ready(function () { $.ajax({ type: "GET", url: "sites.xml", dataType: "xml", success: function (xml) { $(xml).find('art').each(function () { var id = $(this).attr('id'); var name = $(this).find('name').text(); var full = $(this).find('large').text(); var detail = $(this).find('detail').text(); var thumb = $(this).find('thumb').text(); var category = $(this).find('category').text(); var dimensions = $(this).find('dimensions').text(); var description = $(this).find('description').text(); var detailthumb = '<img src= " ' + thumb + ' " />'; var detailfull = '<iframe name= "portfolio ' + name + ' " src=" ' + detail + ' " iframe/>'; var large = '<iframe height="482px" width="786px" class="image-frame" name= "portfolio ' + name + ' " src= " ' + full + ' " />'; $('<div class="art" id="link_' + name +'"></div>').html('<div id="portfolio-content" class="' + name +'"><div class="thumb"><a href= " ' + detail + ' " target= "portfolio ' + name + ' ">' + detailthumb + '<br/></a>(Click for Detail)</div><div class="image">' + large + "</div><div class='text'><h1>" + name + "</h1>" + category + "<br/>" + dimensions + "<br/>" + description + "</div></div>").appendTo('#page-wrap'); }); var $currElement = $("#start"); $currElement.css("background", "red"); $("#nextButton2").click(function () { if(!$currElement.next('div').length){ alert("No element found!"); return false; } $currElement = $currElement.next('div'); $("div,p").css("background", ""); $currElement.css("background", "red"); }); var $currElement = $("#start"); $currElement.css("background", "red"); $("#prevButton2").click(function () { if(!$currElement.prev('div').length){ alert("No element found!"); return false; } $currElement = $currElement.prev('div'); $("div,p").css("background", ""); $currElement.css("background", "red"); }); } }); }); Im currently running out of ideas of how else to attack this. This page will be navigated to by clicking on a thumbnail that will then open that particular element. How do I also get it to open to the correct element in the xml sheet. PLEASE HELP I'm not sure whether this is a javascript or CSS related problem so sorry if I've posted this in the wrong place. I'm modifying a slideshow plugin to fit my website and have changed some of the dimensions of the slides. Now the next slide is coming in from the wrong position on the right hand side. I'm not sure how to fix this, can someone please help? http://ah.mjtippet.com/ I used the tutorial here to create a slideshow but would like to add captions... could anyone help me with the code? Below is part of the script I used... (there are 27 images so I cut it short... head code:<script type="text/javascript"> <!-- var image1=new Image() image1.src="images/pic_1.jpg" var image2=new Image() image2.src="images/pic_2.jpg" var image3=new Image() image3.src="images/pic_3.jpg" body code: <img src="images/pic_1.jpg" name="slide" width=180 height=150> <script> <!-- //variable that will increment through the images var step=1 function slideit(){ //if browser does not support the image object, exit. if (!document.images) return document.images.slide.src=eval("image"+step+".src") if (step<27) step++ else step=1 //call function "slideit()" every 2.5 seconds setTimeout("slideit()",2500) } slideit() //--> </script> I would really appreciate any help as I am a newbie to this... how do i make those two lines go away in the backround? EDIT: UP! http://insidehb.com/main/default.html EDIT: Now works with ie My code works great except that the margin and padding CSS isn't doing anything. Which doesn't make sense to me because the font size, style, and alignment is affected by the CSS. Does anyone know why this is?? Code: <h2 class="sidebar-heading">Testimonial:</h2> <html> <head> <title>Testimonies</title> <style type="text/css"> #quote { margin: 0 20px; padding-top: 20px; font-size: 1.1em; font-style: italic; text-align: left; } </style> <script type="text/javascript" language="javascript"> var testimony = new Array() testimony[1]= "<i>Testimonial 1</i>"; testimony[2]= "<i>Testimonial 2</i>"; testimony[3]= "<i>Testimonial 3</i>"; function firstTestimony() { document.getElementById('div_display').innerHTML=testimony[1]; setTimeout("secondTestimony()",2000); } function secondTestimony() { document.getElementById('div_display').innerHTML=testimony[2]; setTimeout("thirdTestimony()",2000); } function thirdTestimony() { document.getElementById('div_display').innerHTML=testimony[3]; setTimeout("firstTestimony()",2000); } </script> </head> <body> <span id="quote"> <div id="div_display"><script type="text/javascript" language="javascript">firstTestimony();</script></div> </span> </body> </html> Thanks!! Hey guys, Im trying to figure out how to display a string of text beneath the drop down when a specific option is selected. for example: if you select 'Colors' just plain text would appear the drop down and show the list of colors 'red, blue, green, yellow' or if you select 'Fruit' the plain text shows the list of fruit "orange, banana, apple, lemon' Any ideas or can you guys point me in the right direction? I have a similar code except its when you type in a number in a textarea it would output the coressponding data. ok well here's what i want to do i have a bbcode for download links on my forum when this bbcode is parsed, it will display a link under the download link BUT only for the first 3 links so basically i would need a javascript with a counter, that will display some text if the counter is > 3 and then add +1 to the counter normally i would EASILY do this with php, but i can't (bbcodes are parsed not parsed by server on phpbb, and you can't use php code in bbcodes) And since i'm a total newbie with javascript, i need to come here and ask this stupid question :/ thanks for your help! if you still don't understand what i want to do, here is how it would look in php if i could include this code in my phpbb custom bbcode: Code: <? if (empty($compteur)) { $compteur = "1"; } if ($compteur < 4) { echo "bla blah blah"; $compteur = $compteur+1; } ?> hi all, im looking for a script that does the following when the page loads "text1" is displayed. then on the next line 2 seconds later "text2" is displayed and test1 is still displayed. and i need this to go to 5 lines so the final project should look like --- text1 text2 text3 text4 text5 thanks This is a follow up to my older thread, about tables and finding images within them. So after getting some help from "Krupski" I found myself stuck again. I'm trying to go at this rather from an other point of view, instead of getting the cell information I am now trying to get the alt text value. from within the image tag. but being a novice at this well ive hit a wall. My code so far. searches though the table finding the sad images then i want it to display the Alt-text or an other value table_id or similar. also is there a fast way of putting in Alt text like A1,2,3 B1,2,3 etc like an automated loop. (might work on this after the main problem is dealt with) Code: <html> <head> <script type="text/javascript"> var findImg = function(name) { var e = document.getElementsByTagName('img'); var i = e.length; // how many img elements total var str = ''; while (i--) { if (e[i].src.indexOf(name) != -1) // if match... str += e[i].src + '\n'; //...copy to str with a newline } alert(str); // display all matches } function searchFor(){ findImg('smiley%20sad%20Icon.jpg'); // call the function with the name to be matched } </script> </head> <body> <table width="200" border="1"> <tr Id="A"> <td Id="1"><img src="http://www.hencam.co.uk/hencam_forum//extensions/Smile/tango/face-smile.png" Alt="A1"> </td> <td Id="2"><img src="http://www.hencam.co.uk/hencam_forum//extensions/Smile/tango/face-smile.png" Alt="A2"> </td> <td Id="3"><img src="http://www.iconeasy.com/icon/thumbnails/System/Icons%20for%20Developers/smiley%20sad%20Icon.jpg" Alt="A3"></td> </tr> <tr Id="B"> <td Id="1"><img src="http://www.hencam.co.uk/hencam_forum//extensions/Smile/tango/face-smile.png" Alt="B1"></td> <td Id="2"><img src="http://www.iconeasy.com/icon/thumbnails/System/Icons%20for%20Developers/smiley%20sad%20Icon.jpg" Alt="B2"></td> <td Id="3"><img src="http://www.hencam.co.uk/hencam_forum//extensions/Smile/tango/face-smile.png" Alt="B3"></td> </tr> <tr Id="C"> <td Id="1"><img src="http://www.hencam.co.uk/hencam_forum//extensions/Smile/tango/face-smile.png" Alt="C1"></td> <td Id="2"><img src="http://www.hencam.co.uk/hencam_forum//extensions/Smile/tango/face-smile.png" Alt="C2"></td> <td Id="3"><img src="http://www.hencam.co.uk/hencam_forum//extensions/Smile/tango/face-smile.png" Alt="C3"></td> </tr> </table> <br> <input type="button" value="Search" id="Search" onClick="searchFor();"/> </body> </html> Thanks in advance anyone who can help. ~Mark j Hi, may I ask how do you display a line or a sentence when you click the checkbox? I have the ability to remotely upload a text file to a folder on my web server. Periodically during the day I update that file and re-upload it which overwrites the previous file. I am looking for a script to insert in a webpage that will "get" and display the current version of that file on page load. Thanks in advance. Hi I am trying to use stoutlabs content slider on my website. I have a dummy set up here www.mattbbell.com Instead of the numbered navigation i want to have text like home, bio, contact etc The demo can be download here http://stoutlabs.com/demos/class_sli..._slider_v2.zip with all files necessary to make the dummy website you see there... From what i can tell I have to edit the sl_slider_new.js file and make it call a list of divs that i name home, bio, contact I think this is the section i need to edit but i don't know much about javascript.... Code: // -- Number nav setup if(self.options.numNavActive == true){ //create numbered navigation boxes, and insert into the 'num_nav' ul) var numItem = new Element('li', {id: 'num'+i}); var numLink = new Element('a', { 'class': 'numbtn', 'html': (i+1) }); numItem.adopt(numLink); self.options.numNavHolder.adopt(numItem); self.numNav.push(numLink); numLink.set('morph', {duration: 100, transition: Fx.Transitions.linear, link: 'ignore'}); numLink.addEvents({ 'click' : function(){ self.numPress(i); }, 'mouseenter' : function() { this.setStyle('cursor', 'pointer'); } }); //set initial number to active state if(i == self.options.itemNum){ var initNum = self.numNav[i]; initNum.addClass('active'); } } //end if num nav 'active' }); }, thanks! |