JavaScript - Canvas Makes Strange Lines.
wait... why am i here???
Similar TutorialsI have 2 news tickers that I want to show one after the other. They are both widgets (javascript) that I grabbed from the stated website. However to get one to run after the other I felt like I needed a setTimeout(). So I made one of them delayed (ticker8) but instead of JUST appearing after 5000 ms, it appears and EVERYTHING ELSE DISAPPEARS. I know that it's something silly I just can't figure out what it is. The HTML code is below. [CODE] <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script LANGUAGE='JavaScript' type='text/javascript' SRC='http://www.theFinancials.com/syndicated/Free/EXk_EconomicStats_US.js'></script> </head> <body> <div id="ticker6"> <script LANGUAGE='JavaScript' type='text/javascript' SRC='http://www.theFinancials.com/syndicated/Free/EXk_Interest_TBills.js'></script> <script LANGUAGE='JavaScript' type='text/javascript'> document.writeln(EXk_Interest_TBills('0050201336','100%','C9C9C9','yes','6B6B6B','Arial',11,1,'37373 7')); </script> </div> <div id="ticker8"> <script type="text/javascript"> setTimeout("ticker8()", 5000); function ticker8() { <!--START theFinancials.com Content--> <!--copyright theFinancials.com - All Rights Reserved--> document.writeln(EXk_EconomicStats_US('0199604514','100%','C9C9C9','yes','6B6B6B','Arial',11,1,'3737 37')); <!--END theFinancials.com Content--> } </script> </div> </body> </html> [CODE] Would really appreciate some help with this one. Many thanks in advance Hi - if you click on any of these radio boxes an effect happens whereby content is pushed down. Can you tell me what causes this? http://www.emailcraft.com/order-now.html The reason I ask is because I am after this effect and am looking for someone to code it for me - but am not sure how to describe it - thanks a lot I have created a popup for music on a site and works fine in firefox. when I pull the site up in IE8 it makes a noise and thats it. the site: http://www.brumarestate.com/ Code: var gmyWin=null; function popmusic(winURL, winName, winFeatures, winObj) { var theWin; // this will hold our opened window // first check to see if the window already exists if (winObj != null) { // the window has already been created, but did the user close it? // if so, then reopen it. Otherwise make it the active window. if (!winObj.closed) { winObj.focus(); } // otherwise fall through to the code below to re-open the window } // if we get here, then the window hasn't been created yet, or it // was closed by the user. theWin = window.open(winURL, winName, "resizable=0,location=0,status=0,scrollbars=0,width=190,height=25"); return theWin; } and of course onload in body tags <body onLoad="return popmusic('music/music.html')"> any idea's, thanks in advance 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 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> 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 . 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. 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? 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> I guess canvases like inline width/height instead of css width/height. This solved the issue. I'm working on a project that uses HTML5 Canvas and I'm having a strange problem with stretching. I noticed it with images and thought my math might have been wrong but then I took everything out and tried drawing a simple 100x100 square and it's completely stretched out at different proportions. The code for this (small class code)- Code: function Canvas(DOMID, F) { this.Frame = null; this.width = null; this.height = null; this.zoom = null; this.DOM = null; this.ctx = null; this.offset = null; //Constructor this.init = function(DOMID, F) { this.DOM = document.getElementById(DOMID); this.width = $(this.DOM).width(); this.height = $(this.DOM).height(); this.ctx = this.DOM.getContext("2d"); this.zoom = 1; this.offset = {x:0,y:0}; if(F != null) this.setFrame(F); this.onReady(); } //Modifiers this.draw = function() { //this.ctx.drawImage(image, 0, 0); this.ctx.beginPath(); this.ctx.fillStyle = "#ffffff"; this.ctx.rect(0,0,100,100); this.ctx.closePath(); this.ctx.fill(); } this.setFrame = function(F) { this.Frame = F; } //Events this.onReady = function(){} this.init(DOMID, F); } The code calling this function is in an interval- Code: window.goToCanvas = function() { clearTimeout(playInterval); playInterval = setInterval("drawCurrentCanvas()", window.playSpeed); } window.drawCurrentCanvas = function() { index = window.canvasIndex; canvases[index].draw(); } The page can be found here- http://micahwilliams...ewer/viewer.php I'm stumped. I hope someone can see my mistake somewhere. Hi all, I'm new to Javascript, and having an issue with getInterval. For my programming languages class we have to create a simulation of waves breaking on a shore from above. I've decided to use a canvas object and Javascript for this animation, but am getting stuck on refreshing the frames. Here is the code I have so far: Code: var shoreline = new Array(); var waves = new Array(); var canWidth = 600; var canHeight = 400; var waveNum = 0; var count = 0; function wave() { setupShore(); var canvas = document.getElementById("canvas"); canvas.setAttribute("width",canWidth); canvas.setAttribute("height",canHeight); var ctx = canvas.getContext("2d"); createWave(); setInterval(update(ctx), 1000); } function update(ctx) { if(waves.length != 0) { drawWater(ctx); drawShore(ctx); drawWaves(ctx); updateWaves(); } } function drawElement(ctx, x, y, width, height, fillcolor) { ctx.fillStyle = fillcolor; ctx.fillRect(x, y, width, height); } function setupShore() { for(var i = 0; i <= canWidth/5; i++) { shoreline[i] = Math.round(canHeight/5); // + Math.floor(Math.random()*101); } } function createWave() { /* Wave array setup: [ [waveID1, [node1, node2, ..., nodeN]], [waveID2, [node1, node2, ..., nodeN] ] */ waves.push([waveNum, []]); for(var c = 0; c <= canWidth/5; c++){ waves[waves.length-1][1].push(canHeight); } waveNum = waveNum + 1; } function destroyWave() { waves.shift(); } function drawWater(ctx) { drawElement(ctx, 0, 0, canWidth, canHeight, "#336699"); } function drawShore(ctx) { for(var s = 0; s <= shoreline.length; s++) { drawElement(ctx, s*5, 0, 5, shoreline[s], "#FFCC00"); } } function updateWaves() { for(var u = 0; u < waves.length; u++) { var limit = waves[u][1].length; for(var v = 0; v < limit; v++){ var temp = waves[u][1][v]-5; waves[u][1][v] = temp; if(waves[u][1][v] <= shoreline[v]){ destroyWave(); } } } } function drawWaves(ctx) { for(var w = 0; w < waves.length; w++) { for(var n = 0; n <= waves[w][1].length; n++){ y = waves[w][1][n]; drawElement(ctx, n*5, y, 5, 5, "Purple"); } } } As you can see, the idea is that each 5-pixel wide node of the shore and wave are stored in arrays so that the position of each node can differ. The wave() function initializes all the required data, and then calls setInterval on update(). The function update() draws the water, shore, and wave, and then updates the wave position node-by-node. Ideally, setInterval would cause this to happen repeatedly, so that the wave would appear to move closer to the shore every 1000ms. However, this is not the case. It appears as though setInterval is working for one pass of update(), but fails after the first pass. You can tell that this is happening because the wave appears at its starting position, but does not continue to move. Any idea why this is happening? I read somewhere that setInterval can be broken by one-time functions, but I'm not sure. If you'd like to see what it's currently doing in a browser, I've hosted it here. Once I've got this animating properly I can continue my project, but I've hit a roadblock. Thanks in advance for your help, I'm really stuck. Marcus So I'm creating a game and decided to use a canvas for the map. The map is a big pictures 500kb+ (6400x6400px) and the canvas size is 320x320 so I am displaying only part of the image at a time and have the page reload on button click for database purposes. What I'd like help with is performance. Currently it's taking a few secs to reload every time and it seems that it causes some cpu strain (can't switch tabs while loading). Could I stop the canvas from reloading the image each time the page is reloaded and if so then how? Can I make the canvas only load a part of the image, if so then how? If neither is possible any tips, solutions how to solve the performance issues? 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?
I found a great little starfield script made with javascript and canvas3d. however i can't for the life of me figure out how to implement a background image inside the canvas. is there some command that tells it to use some feature of canvas, that if otherwise not called, won't allow normal graphics? his whole starfield is generated with a search engine form , and appears to just use a text period to represent stars. here's a link to his script: http://seb.ly/demos/canvas3d/canvas3d2.html how do i get a background image in that? or is it impossible? i tried putting it in the body tag, but it just flashed the background image on the screen for a half a second and then went back to showing only the black background. i tried removing the background body color and replacing it with only background-image ccs, same problem. i tried div positioning it, but the div just covered up the starfield. 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 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> not sure if this is the right place to ask canvas questions, but if it is, i'm trying to program a game like air hockey (with some twists). it works pretty well now but the table is viewed from overhead, and i would prefer to show the game from the player's perspective, as in the pic, without having to rewrite my existing code. anyone know of any js libraries or formulas which can accomplish this? Hello, I have this idea, but I wouldn't want to reinvent the wheel if it's already been done. I want to generate perspective grid on canvas depending on browser window size, something like this, but without textures: http://www.123rf.com/photo_2651286_a...rspective.html Do someone of you guys know if some similar script already exists? Or at least some tips on how not to end up writing a 1000 lines script (At this point I would just drop the idea)? All thoughts appreciated. P.S. even an obscure algorithm would probably suffice, 'cause the main problem I'm struggling with is diminishing size perspective calculations |