JavaScript - Math.random And Fillrect With Html5 Canvas
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! 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've looked for a solution to this issue, but it seems like a little different scenario than other situations. I made a system for generating friend requests on Facebook. I have a grid that is 6 x 3, for a total of 18 cells. Each cell has a picture in it, and the picture is linked to the Facebook friend request page. My problem is that since each cell is populated at random from the array, I'm getting lots of repeats. For example, some picutures are in 5 cells, and some are in none. I'm trying to figure out how to make it so that once a picture is used once in the grid, it does not get used again in the same grid. I still want every cell filled at random on each page load, I just want to prevent the repeating. Here's my current code: Code: <script type="text/javascript"> var vip_list=new Array( new Array('http://profile.ak.fbcdn.net/v225/1616/88/s1220771654_2158.jpg','http://www.facebook.com/addfriend.php?id=1220771654'), new Array('http://profile.ak.fbcdn.net/v223/1233/29/s904885342_9055.jpg','http://www.facebook.com/addfriend.php?id=904885342'), new Array('http://profile.ak.fbcdn.net/v229/1574/66/s1752031238_626.jpg','http://www.facebook.com/addfriend.php?id=1752031238'), new Array('http://profile.ak.fbcdn.net/v223/768/71/n661155042_7325.jpg','http://www.facebook.com/addfriend.php?id=661155042'), new Array('http://profile.ak.fbcdn.net/v226/732/26/n1827289885_2478.jpg','http://www.facebook.com/addfriend.php?id=1827289885'), new Array('http://profile.ak.fbcdn.net/v229/1631/70/s1425313768_1140.jpg','http://www.facebook.com/addfriend.php?id=1425313768'), new Array('http://static.ak.fbcdn.net/pics/s_silhouette.jpg','http://www.facebook.com/addfriend.php?id=1667023416'), new Array('http://profile.ak.fbcdn.net/v225/1146/29/s506485704_9532.jpg','http://www.facebook.com/addfriend.php?id=506485704'), new Array('http://profile.ak.fbcdn.net/profile6/270/32/s692160490_8745.jpg','http://www.facebook.com/addfriend.php?id=692160490'), new Array('http://profile.ak.fbcdn.net/v229/114/83/s1218176198_7375.jpg','http://www.facebook.com/addfriend.php?id=1218176198'), new Array('http://profile.ak.fbcdn.net/v226/946/4/s1470171885_4973.jpg','http://www.facebook.com/addfriend.php?id=1470171885'), new Array('http://static.ak.fbcdn.net/pics/s_silhouette.jpg','http://www.facebook.com/addfriend.php?id=1329505888'), new Array('http://static.ak.fbcdn.net/pics/s_silhouette.jpg','http://www.facebook.com/addfriend.php?id=1325496968'), new Array('http://profile.ak.fbcdn.net/v223/1546/92/s1536913202_2017.jpg','http://www.facebook.com/addfriend.php?id=1536913202'), new Array('http://static.ak.fbcdn.net/pics/s_silhouette.jpg','http://www.facebook.com/addfriend.php?id=1624715433'), new Array('http://profile.ak.fbcdn.net/v228/1282/58/s713998257_3682.jpg','http://www.facebook.com/addfriend.php?id=713998257') ); var chosen_vip=Math.floor(vip_list.length*Math.random()); var chosen_vip1=Math.floor(vip_list.length*Math.random()); var chosen_vip2=Math.floor(vip_list.length*Math.random()); var chosen_vip3=Math.floor(vip_list.length*Math.random()); var chosen_vip4=Math.floor(vip_list.length*Math.random()); var chosen_vip5=Math.floor(vip_list.length*Math.random()); var chosen_vip6=Math.floor(vip_list.length*Math.random()); var chosen_vip7=Math.floor(vip_list.length*Math.random()); var chosen_vip8=Math.floor(vip_list.length*Math.random()); var chosen_vip9=Math.floor(vip_list.length*Math.random()); var chosen_vip10=Math.floor(vip_list.length*Math.random()); var chosen_vip11=Math.floor(vip_list.length*Math.random()); var chosen_vip12=Math.floor(vip_list.length*Math.random()); var chosen_vip13=Math.floor(vip_list.length*Math.random()); var chosen_vip14=Math.floor(vip_list.length*Math.random()); var chosen_vip15=Math.floor(vip_list.length*Math.random()); var chosen_vip16=Math.floor(vip_list.length*Math.random()); var chosen_vip17=Math.floor(vip_list.length*Math.random()); document.write('<center>'); document.write('<a href="',vip_list[chosen_vip][1],'" target="_blank"><img src="',vip_list[chosen_vip][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip1][1],'" target="_blank"><img src="',vip_list[chosen_vip1][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip2][1],'" target="_blank"><img src="',vip_list[chosen_vip2][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip3][1],'" target="_blank"><img src="',vip_list[chosen_vip3][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip4][1],'" target="_blank"><img src="',vip_list[chosen_vip4][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip5][1],'" target="_blank"><img src="',vip_list[chosen_vip5][0],'" height="60" width="60"></a>'); document.write('<br>'); document.write('<a href="',vip_list[chosen_vip6][1],'" target="_blank"><img src="',vip_list[chosen_vip6][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip7][1],'" target="_blank"><img src="',vip_list[chosen_vip7][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip8][1],'" target="_blank"><img src="',vip_list[chosen_vip8][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip9][1],'" target="_blank"><img src="',vip_list[chosen_vip9][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip10][1],'" target="_blank"><img src="',vip_list[chosen_vip10][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip11][1],'" target="_blank"><img src="',vip_list[chosen_vip11][0],'" height="60" width="60"></a>'); document.write('<br>'); document.write('<a href="',vip_list[chosen_vip12][1],'" target="_blank"><img src="',vip_list[chosen_vip12][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip13][1],'" target="_blank"><img src="',vip_list[chosen_vip13][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip14][1],'" target="_blank"><img src="',vip_list[chosen_vip14][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip15][1],'" target="_blank"><img src="',vip_list[chosen_vip15][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip16][1],'" target="_blank"><img src="',vip_list[chosen_vip16][0],'" height="60" width="60"></a>'); document.write('<a href="',vip_list[chosen_vip17][1],'" target="_blank"><img src="',vip_list[chosen_vip17][0],'" height="60" width="60"></a>'); document.write('<br>'); </script> Any suggestions? Thank you! 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); } 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. 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 hey. im working on a facebook app.. this is what i got so far. PHP Code: <script language="JavaScript"> <!-- var theImages = new Array() theImages[0] = "http://img688.imageshack.us/img688/4787/logo1tq.jpg" theImages[1] = "http://img641.imageshack.us/img641/8292/logo2yex.jpg" theImages[2] = "http://img864.imageshack.us/img864/4097/logo3ik.jpg" theImages[3] = "http://img543.imageshack.us/img543/9046/logo4pu.jpg" theImages[4] = "http://img21.imageshack.us/img21/2567/logo5q.jpg" theImages[5] = "http://img842.imageshack.us/img842/696/logo6o.jpg" theImages[6] = "http://img85.imageshack.us/img85/7831/logo7k.jpg" var j = 0 var p = theImages.length; var preBuffer = new Array() for (i = 0; i < p; i++){ preBuffer[i] = new Image() preBuffer[i].src = theImages[i] } var whichImage = Math.round(Math.random()*(p-1)); function showImage(){ document.write('<img src="'+theImages[whichImage]+'">'); } //--> </script> <script language="JavaScript"> <!-- showImage(); //--> </script> now i want that the app posts the random image automaticlly to the useres timeline.. for example: if the random image is theImages [3] then it should post the image theimage [3] to the users timeline.. i see alot of facebook apps doing this.. thanks in advance I'm a newby that just finished an online javascript course. When I do a search on Math.random() I receive sites that all describe the command as returning a number 'between 0 and 1'. My question is - are the expected numbers limited to - 0.0000000000000001 thru 0.9999999999999999 or is it possible to get the 0 and 1 also. Seems like the definition should be 'from 0 thru 1' rather than 'between 0 and 1'. JoeF With HTML5, I can specify the form input to have type="number". This brings up the numeric keyboard instead of the standard text keyboard. However, there are a couple problems: - On the iPhone, it will add commas. This is when entering values, but when you start to remove values, the commas do not update their positions. This creates a NaN issue. - If I have the output set to toPrecision or toExponential, it seems to ignore this and force the number to be a standard number. That said, I simply want to bring up the numeric keyboard, without the other "logic" that it is trying to do (which messes me up). Any ideas? Have others observed this frustrating behavior? Hi there! How should I write this - better than it's now - so that when I rotate a figure, in the next "frame" it would stay rotated? Second thing - if you run this code, and set the angle for, let's say 180 degrees the figure is being drawn in some random location. How do I fix this? Code: Code: function GenericFigure(context) { this.states = ["wait", "moving", "rotating", "stop"]; this.state = this.states[0]; this.ctx = context; this.sqrW = this.sqrH = 20; this.ctxW = 200; this.ctxH = 350; this.colorsO = { red : "#ee1515", green : "#45d137", blue : "#17a3f3", orange : "#ff910f", purple : "#680077" }; this.colorsA = ["#ee1515", "#45d137", "#17a3f3", "#ff910f", "#680077"]; this.pickColor = function() { var num = Math.floor(Math.random() * 5); return this.colorsA[num]; } } function Rectangle(context) { this.inheritFrom = GenericFigure; this.inheritFrom(context); this.width = this.sqrW; this.height = this.sqrH * 3; this.x = this.ctxW / 2; this.y = 0; this.rotation = -1; this.setRotation = function(angle) { this.rotation = angle; } this.rotate = function() { this.ctx.clearRect(0, 0, this.ctxW, this.ctxH); this.ctx.translate(this.x + 2 * this.width, this.y - 2 * this.height + 20); this.ctx.rotate(this.rotation * Math.PI / 180); this.ctx.fillRect(this.ctxW / 2, 0, this.width, this.height); this.ctx.restore(); } this.moveDown = function() { this.y += 20; this.ctx.restore(); this.ctx.clearRect(0, 0, this.ctxW, this.ctxH); this.ctx.fillRect(this.x, this.y, this.width, this.height); this.ctx.save(); if(this.rotation > -1) { this.rotate(); } l("A"); } this.draw = function() { this.ctx.fillStyle = this.pickColor(); this.ctx.save(); this.ctx.fillRect(this.x, this.y, this.width, this.height); } } //a tak można wywołać: var ctx = document.getElementById("game").getContext("2d"); var rect = new Rectangle(ctx); rect.draw(); var inte = setInterval(function(){if(rect.y >= rect.ctxH - rect.height){clearInterval(inte);return;}if(rect.y == 60) rect.setRotation(90);rect.moveDown();}, 500); And the third problem: Code: this.ctx.translate(this.x, 0); I thought, that this line should set orientation point to top left corner of my figure, but it seems, that it doesn't - after rotation my figure is being drawn two heights lower. Again - how do I fix it? Any help will be much appreciated . Hey everyone, I have been practicing using canvas to make designs. My current code below will load the word the user inputs and makes it bounce around the canvas as well as a text spinner. However, whenever the user inputs a second word, the bounce below stops to start a new one and the text spinner messes up. I was wondering if anyone could help me so when the user inputs another word, that it either reloads a new textspinner or adds another one, as well as just add the word to the canvas without stopped the old one. Here's my current script. Thanks already, Joey Code: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script> var ctx; var a=0.0; var as=true;//true a is increasing, false decreasing var x,y; var xs = 1; var ys = 1; var userWord var myDiv, t; var test = 0; var ds ="";//display string var sli =0; //spinning letter index; function init(){ ctx = document.getElementById("myCvs").getContext("2d"); userWord = document.getElementById("userWord").value; x=Math.floor(Math.random()*801) y=Math.floor(Math.random()*601); drawText(); setInterval("onEnterFrame()", 50); myDiv = document.getElementById("myDiv"); for (i =0; i<=userWord.length;i++){ ds += "*"; } myDiv.innerHTML =ds; textSpin(); } function textSpin(){ myChar = randomChar(); var newString = userWord.slice(0, sli); newString +=myChar; newString += ds.slice(sli+1, ds.length-1); myDiv.innerHTML = newString; if (myChar == userWord.charAt(sli)){sli++;} if (sli<userWord.length){ t = setTimeout("textSpin()", 80); } } function randomChar(){ var rc = Math.random()*26 + 97; //random lowercase char code return String.fromCharCode(rc); } function onEnterFrame(){ if(a>1){as = false;} if(a<0){as = true;} if(as){ a+=0.01; }else{ a-=0.01; } if(x>800){xs = -1} if(x<0){xs=1} if(y>600){ys = -1} if(y<0){ys=1} x+=10 *xs; y+=10 *ys; drawText(); } function drawText(){ ctx.font = "20px Times New Roman"; //ctx.fillStyle= "rgb(256,256,256)"; //ctx.fillText("Hello", x, y); ctx.fillStyle = randomColor(); ctx.fillText(userWord, x,y); } function randomColor(){ var r = Math.floor(Math.random()*150)+55; var g = Math.floor(Math.random()*256)+150; var b = Math.floor(Math.random()*20)+50; var a = Math.random(); return "rgba("+ r+ ","+g+","+b+","+ a+")"; } //function randomFont(){ // var s = Math.floor(Math.random()*100) +100; // return s; //+ "px Times New Roman";} </script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> body { background-color:#000; } #myDiv { color:#FFF; } </style> </head> <body onLoad=""><center> <input type="text" id="userWord" value=""> </input><br> <input type="button" id="enterWord" value="Enter Word" onClick="init()" ></input><br><br> <div id="myDiv" > </div> <canvas id="myCvs" width="800px" height="600px" /><br> <br> </center> </body> </html> I've been reading a lot of tutorials on the canvas tag and seen a lot of people using JavaScript that looks something like: ctx.beginPath(); ctx.moveTo(25,25); ctx.lineTo(105,25); ctx.fill(); I understand that ctx is just the variable name and I can replace that with any variable I define, however, I'm looking for a list of all of the methods such as (moveTo, lineTo, fill etc...), as well as what they do. I hope I'm explaining this or asking this correctly. Thanks! -Mike Hello guys! I need your help! I want to create a rectangle with a line in the middle with the canvas object. The problem is that the line in the middle gets bigger than the rest of the rectangle. How do I solve this? I believe it has something to do with shadows. If so, how do I turn them off. My code is: <html> <head> <title></title> </head> <body> <canvas id='chart' width='400' height='200'> <script type="text/javascript"> var canvas = document.getElementById('chart'); var ctx = canvas.getContext('2d'); ctx.lineWidth = 10; ctx.strokeRect(0, 0, 400, 200); ctx.moveTo(0, 100); ctx.lineTo(400, 100); ctx.stroke(); </script> </body> </html> So I've been making a game using html canvas. Here is a link to the game. (Move around with wasd, rotate turret with left and right arrows) http://db.tt/ei3LlR The problem is that the shadow flickers when it is rotated. This does not happen in firefox. The shadow is not an image, but another canvas element, generated dynamically from the image of the tank. So the problem seems to be with webkit drawing rotated canvas elements inside another. Could this possibly be the reason behind this, or is it more likely to be a problem on my end? I just cant wrap my mind around canvas. As far as I can tell theres no logical reason as to why the code would not work. Could someone take a look at it and possibly figure out whats wrong? I'm trying to intialize and draw a canvas with a simple image. I have the functions in a custom namespace in javascript. I am also using Jquery Code: var birdr = new Image(); var birdl = new Image(); $(document).ready(function(){ if(Modernizr.canvas){ var c = document.createElement('canvas'); LK.animLoad(); document.getElementById('backg-canvas').appendChild(c); $('canvas').attr({'width':'500','height':'500','id':'canvas'}); var context = LK.returnCanvas(); context.drawImage(birdl, 400,487,10,10); } }); var LK = { birdx: 400, //unused (lets just get it to draw the image first :\) birdy: 487, //unused animLoad: function(){ birdl.src = "images/bird2.png"; birdr.src = "images/bird.png"; //alert(birdl); //alert(birdr); }, returnCanvas: function(ca){ var b_canvas = LK.getCanvas(); var b_context = b_canvas.getContext('2d'); return b_context; }, getCanvas: function(){ var a_canvas = document.getElementById('canvas'); //alert(a_canvas); return a_canvas; } } Any help would be greatly appreciate thanks. Btw safari web inspector indicates the canvas is getting properly created and appended to the container div. So that all works fine. Anyone got any suggestions on techniques? The main one I find is to use translate to move the canvas around, which just seems odd to me. I don't even fully understand how it works. But the one I was looking at used clearRect. In examples given looked as though it had to redraw the canvas every frame. I'm just mucking around with a simple poker game, figured i'd have the table in one layer and anything that moves on a top layer? By doing that I could only clear each card as it moved around...yes? Anyone know of a better way of doing things? Code: <form> <input id="a" size=4 name="neg" placeholder="1st Screen size in inch"> <input id="b" size=4 name="hoyr" placeholder="2nd Screen size in inch"> <input type="submit" value="GO!" onclick="getValue()"> </form> </div> <canvas id="MyCanvas" width="1000" height="1000"></canvas> <script type="text/javascript"> function getValue() { var x = document.getElementById("a").value; var y = document.getElementById("b").value; var aWidth; var aHeight; var bWidth; var bHeight; var c= document.getElementById("MyCanvas"); var ctx= c.getContext("2d"); ctx.fillStyle="#4AA02C"; ctx.fillRect(0,0,x,y); } Here, it draws canvas then disappears immediately. Hello, Codingforums. I have looked on Google for a solution, done a handful of things, and cannot get my script to draw to the page. Code: <html> <head> <script type="text/javascript" src="imageFuncs.js"></script> <script type="text/javascript"> showImages = function() { var drawingCanvas = document.getElementById("map"); // Check the element is in the DOM and the browser supports canvas if (drawingCanvas.getContext) { var ctx = drawingCanvas.getContext("2d"); var imageSources = new Array("map.jpg"); var images = new Array(); images = loadImages(imageSources); for (var i = 0; i < images.length; i++) { var img = new Image(); img.src = images[i].src; img.onload = function(){ ctx.drawImage(img,0,0,screen.width,screen.height); } } } } </script> </head> <body onload="showImages()"> <canvas id="map">Your browser does not support canvases...</canvas> </body> </html> The problem appears on the ctx.drawImage(img,0,0,screen.width,screen.height); line. I read that the drawImage method will not draw the image if the images are not loaded, which is why I tried an onload event for img. When I run the code the way it is now, I get a attempt to run compile-and-go script on a cleared scope error from Firebug. When I remove the onload event, the script runs without errors. Either way, no image is drawn on the page. Any help? If it helps, this is the loadImages function that I used to get the array of loaded image objects: Code: function loadImages(sources){ var images = new Array(); var loadedImages = 0; var numImages = 0; for (var src in sources) { numImages++; } for (var src in sources) { images[src] = new Image(); images[src].src = sources[src]; } return images; } Hi. I'm writing a script that graphs data in different colors and shapes and I'm encountering two problems: (1) I can't specify different colors for the graph I'm rendering. If I use fillStyle="red"; then the entire chart becomes red. It seems to use the last color specified as the color for everything on the chart. (2) The shapes are overlapping in strange ways. The fills are not covering the lines of shapes behind them so it's unclear which shape is in front and which is behind. It's like they aren't being treated as separate shapes but instead one shape where boundaries are unclear. I don't know how else to explain it. I'm hoping there is some way to put each shape in its own layer. Would I have to use DIV IDs for that or is there a way to keep it all in the script so it's more scalable? I have make a javascript program that uses HTML canvas and I can't get it to work in Internet Explorer. I tried using excanvas and jqcanvas but had trouble getting them to work. Does anyone know how to do this?
|