JavaScript - Formatting A String In Different Colors With Canvas:filltext(...)
How do I format a string in different colors with canvas:fillText(...);
I want the following result: str = "This is blue", where "This is" is black color and "blue" is blue color. Similar TutorialsI have a Number as a String. It goes from 1 to 999 but I need to set the format so that it has leading Zeros. So 1 is 001 and 2 is 002 and 99 is 099. Is there a way to do this in JavaScript? Thanks, ~Dave 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 . 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? 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. 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. 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? 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 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; } 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. 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?
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? I made a graphing calculator using canvas in javascript. It's pretty simple as of right now. I was hoping you guys could take a look and tell me what types of things I should add. Some I'm already looking into: customizable x-min, x-max, etc., plotting more than one function on the same graph. It supports sin(), cos(), tan(), pi, e, sqrt(), ln(), abs(), acos(), asin(), atan(). Exponents can be written as b^e. Please give me some suggestions. http://jazzothegreat.com/graph.html Thanks, Julian 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? 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> i want to transfrom image like the picture below using canvas,it seems simple but i find no way to do , can anyone give me some ideas? ( left side is the source) 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. |