Error: Not getting a desired output - javascript

I am looking to print a red circle when the string contains a character 'e' and a black circle if it contains any other character.
I do not know where exactly I am getting it wrong. Can someone help me?.
This is the code I tried.
HTML
<input id="e-" placeholder="type eg:-e---ee---e" type="text" size="50"/>
<button onclick="start()">diagram</button>
<canvas id="myCanvas"></canvas>
The JavaScript
function start() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var str = getElementByID("e-");
var i;
for( i=0; i < str.length(); i++ ) {
if( str.charAt(i) == "e" ) {
ctx.beginPath();
ctx.arc(100, 75, 10, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
ctx.stroke();
} else {
ctx.beginPath();
ctx.stroke();
ctx.arc(100, 75, 10, 0, 2 * Math.PI);
ctx.fillStyle = "black";
ctx.fill();
}
}
}

You have several errors here. I'll comment in the live code below:
function start() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d")
// must be prefixed with document., small d in Id, and suffixed with value
var str = document.getElementById("e-").value;
var i = 0, ch;
while(ch = str[i++]) { // no () behind length, changed to while loop
ctx.beginPath();
if (ch === "e") { // just check straight
ctx.arc(100, 75, 10, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
ctx.stroke();
} else {
ctx.arc(100, 75, 10, 0, 2 * Math.PI);
ctx.fillStyle = "black";
ctx.fill();
}
// need to move the arc position on x axis
ctx.translate(22, 0); // diameter + 2 pixels
}
ctx.setTransform(1,0,0,1,0,0); // reset translate
}
<input id="e-" placeholder="type eg:-e---ee---e" type="text" size="50" />
<button onclick="start()">diagram</button>
<canvas id="myCanvas" width=600 ></canvas>

Related

2048 in javascript: updating the canvas

I am in a computer science class at my high school, and for my final project, my partner and I have decided to make 2048. We are not going to have the tiles "move", but instead, the 4x4 board will have "tiles" that are have properties of the number and color of the "tile" as it appears on the board. We are able to get the x and y coordinates of a tile to change, but the canvas will not update. We have had this problem for two weeks now, and have tried everything, but nothing has worked. Our code is posted below.
Please keep in mind that as we have only used javascript for a couple months, and only to do very simple things, our understanding is limited. Thank you for your help.
<!DOCTYPE html>
<html lang = "en">
<body style="background-color:lightgrey;">
<title>2048</title>
<canvas id="myCanvas" width="410" height="410" style="border:1px solid #d3d3d3;">
</canvas>
<script>
var x = 10;
var y = 10;
document.addEventListener('keydown', function(event)
{
if(event.keyCode == 37)//left
{
x -= 100;
console.log("x:"+ x);
}
else if(event.keyCode == 38)//up
{
y -= 100;
console.log("y:"+ y);
}
else if(event.keyCode == 39)//right
{
x += 100;
console.log("x:"+ x);
}
else if(event.keyCode == 40)//down
{
y += 100;
console.log("y:"+ y);
}
});
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// grey rectangle
ctx.beginPath();
ctx.lineWidth = "2";
ctx.strokeStyle = "grey";
ctx.rect(5, 5, 400, 400);
ctx.stroke();
// blue rectangle
ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "blue";
ctx.rect(x, y, 100, 100);
ctx.stroke();
ctx.fillStyle = "blue";
ctx.fill();
</script>
</body>
</html>
What your game needs is a game loop. So the drawing needs to happen continously, at the moment you draw only one time at the beginning.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
function draw() {
// clear the canvas so the old rectangles are gone
ctx.clearRect(0, 0, c.width, c.height);
// grey rectangle
ctx.beginPath();
ctx.lineWidth = "2";
ctx.strokeStyle = "grey";
ctx.rect(5, 5, 400, 400);
ctx.stroke();
// blue rectangle
ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "blue";
ctx.rect(x, y, 100, 100);
ctx.stroke();
ctx.fillStyle = "blue";
ctx.fill();
}
// repeat game loop function forever, 30 times per second
window.setInterval(draw, 1000.0 / 30.0)
Notice the use of window.setInterval and ctx.clearRect.
Every time you want to update what is shown on the canvas, you have to 'Draw' again. Your code will run once when the page loads but never draws again so your changes to x and y are never seen.
I added a draw function here that is called on startup and after each keydown.
<!DOCTYPE html>
<html lang = "en">
<body style="background-color:lightgrey;">
<title>2048</title>
<canvas id="myCanvas" width="410" height="410" style="border:1px solid #d3d3d3;">
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = 10;
var y = 10;
document.addEventListener('keydown', function(event)
{
if(event.keyCode == 37)//left
{
x -= 100;
console.log("x:"+ x);
}
else if(event.keyCode == 38)//up
{
y -= 100;
console.log("y:"+ y);
}
else if(event.keyCode == 39)//right
{
x += 100;
console.log("x:"+ x);
}
else if(event.keyCode == 40)//down
{
y += 100;
console.log("y:"+ y);
}
draw();
});
function draw(){
ctx.clearRect(0, 0, c.width, c.height);
// grey rectangle
ctx.beginPath();
ctx.lineWidth = "2";
ctx.strokeStyle = "grey";
ctx.rect(5, 5, 400, 400);
ctx.stroke();
// blue rectangle
ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "blue";
ctx.rect(x, y, 100, 100);
ctx.stroke();
ctx.fillStyle = "blue";
ctx.fill();
}
draw();
</script>
</body>
</html>

how to make an object turn around a point in html5 canvas

The problem is demonstrated in the image below
In other words, how to exactly compute the x and y coordinates for every frame?
ctx.arc(x,y,radius,0,pi*2,false)
because after incrementing one coordinate, I have a problem how to compute the other
I tried this but doesn't work
var step=2,x=100,y=100,r=50,coordinates=[[x,y-r]];
for(var i=1;i <r;i+=step){
bx=x;
x+=step;
y=y-Math.sqrt(Math.pow(r,2)-Math.pow(bx-x,2))
coordinates[i]=[x,y];
}
a jsfiddle will be appreciated.
var canvas = document.querySelector("#c");
var ctx = canvas.getContext("2d");
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var speed = 10; // Lower is faster
function animate(t){
ctx.save();
ctx.clearRect (0 , 0 ,canvas.width ,canvas.height );
ctx.translate(canvas.width/2, canvas.height/2);
// First circle
ctx.beginPath();
ctx.arc(0, 0, 5, 0, 2 * Math.PI, false);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();
// rotate + move along
ctx.rotate((t/speed)/100);
ctx.translate(100,0);
// Orbiting cirle
ctx.beginPath();
ctx.arc(0, 0, 10, 0, 2 * Math.PI, false);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
ctx.restore();
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
canvas {
border: 1px solid black;
}
<canvas id="c" width="512" height="512"></canvas>

Change images Timeout Loop Javascript

I have two images, green and black. I want to alternate those images in a certain frequency.
My code:
<script>
var wis=1;
var delay=500;
wissel()
function wissel() {
if (wis==1)
{wis=2; green();}
else {wis=1; black();}
delay=delay+500;
setTimeout (wissel(), delay)
}
function green() {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(438,398,125,0,2*Math.PI);
ctx.arc(838,398,125,0,2*Math.PI);
ctx.fillStyle="#00ff00";
ctx.fill();
}
function black() {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(438,398,128,0,2*Math.PI);
ctx.arc(838,398,128,0,2*Math.PI);
ctx.fillStyle="#000000";
ctx.fill();
}
</script>
When I insert an alert(wis) behind the delay=delay+500; line it works. But of course I do not want to click. I want it automatically. I can use some help here.
You have mistake in your setTimeout call. Remove the parentheses:
DEMO
var wis = 1;
var delay = 500;
wissel()
function wissel() {
if (wis == 1) {
wis = 2;
green();
} else {
wis = 1;
black();
}
delay = delay + 500;
setTimeout(wissel, delay)
}
function green() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(438, 398, 125, 0, 2 * Math.PI);
ctx.arc(838, 398, 125, 0, 2 * Math.PI);
ctx.fillStyle = "#00ff00";
ctx.fill();
}
function black() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(438, 398, 128, 0, 2 * Math.PI);
ctx.arc(838, 398, 128, 0, 2 * Math.PI);
ctx.fillStyle = "#000000";
ctx.fill();
}

How to divide the Circles into 24/7 equal parts using canvas?

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Growing Circles</title>
</head>
<body>
<canvas id="c" width="960" height="720"></canvas>
</body>
</html>
JavaScript
var canvas = document.getElementById( "c" ),
ctx = canvas.getContext( "2d" );
ctx.lineWidth = 3;
ctx.beginPath();
ctx.arc( 500, 350, 60, 0, 2 * Math.PI, false );
ctx.fillStyle = "#4DA54D";
ctx.fill();
ctx.strokeStyle = "DarkRed";
ctx.stroke();
ctx.beginPath();
ctx.arc( 500, 350, 120, 0, 2 * Math.PI, false );
ctx.strokeStyle = "OliveDrab";
ctx.stroke();
ctx.beginPath();
ctx.arc( 500, 350, 180, 0, 2 * Math.PI, false );
ctx.strokeStyle = "#530053";
ctx.stroke();
ctx.beginPath();
ctx.arc( 500, 350, 240, 0, 2 * Math.PI, false );
ctx.strokeStyle = "#208181";
ctx.stroke();
ctx.beginPath();
ctx.arc( 500, 350, 300, 0, 2 * Math.PI, false );
ctx.strokeStyle = "#CC7A00";
ctx.stroke();
ctx.beginPath();
ctx.arc( 500, 350, 360, 0, 2 * Math.PI, false );
ctx.strokeStyle = "#205450";
ctx.stroke();
I want to divide This demo into 24 hours timeline by using lines. I tried few but not up-to mark.It is going very big in code!
Is there any other way to solve this in small piece of code like using slice as in Tried demo ?
Tried Demo
My Requirement is to do as This demo.
I want to have This demo to be sliced 24/7 where 24 represent hours and 7 for days.
Further Requirement :: Even i must be able to access the particular arc which i want depending on the day and hour !
Finally i want to have a look like this Image I will pass the arguments(Day, hour,Color) and then that particular segment should change the color, as i shown in the Image.
This is how i tried to print the numbers ..
function drawnumbers(){
for(var i=1; i< hours+1;i++){
context.font="18px sans-serif";
context.fillText(+i,20+i*30,20+i*30);
}
}but i want them on the outer circle as in png Image
Although Harsh has already provided a very useful answer, it relates to the wireframe drawing which you depicted.
I thought it would also be useful to show you how you could achieve the drawing of the individual segments.
I think you have asked for a little too much in your PNG as we would practically be creating your project for you, but with my answer and Harsh's answer I believe you can get what you want:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// centre or center for US :) the drawing
var x = canvas.width / 2;
var y = canvas.height / 2;
// number of days
var days = 7;
// number of hours
var hours = 24;
// one segment represents an hour so divide degrees by hours
var segmentWidth = 360 / hours;
// begin at 0 and end at one segment width
var startAngle = 0;
var endAngle = segmentWidth;
// how thick you want a segment
var segmentDepth = 30;
function init() {
for (var i = 1; i <= days; i++) {
drawSegments(i * segmentDepth);
}
}
function drawSegments(radius) {
for (var i = 0; i < hours; i++) {
context.beginPath();
context.arc(x, y, radius,
(startAngle * Math.PI / 180), (endAngle * Math.PI / 180), false);
context.lineWidth = segmentDepth;
context.strokeStyle = '#' +
(Math.random() * 0xFFFFFF << 0).toString(16);
context.stroke();
// increase per segment
startAngle += segmentWidth;
endAngle += segmentWidth;
}
}
// start drawing our chart
init();
See my http://jsfiddle.net/U2tPJ/6/ demo.
Man, you are doing PROGRAMMING, so why are you afraid of using the tools? Use loops and variables.
Dial
var canvas = document.getElementById( "c" ),
ctx = canvas.getContext( "2d" ),
strokes = ["DarkRed", "OliveDrab", "#530053", "#208181", "#CC7A00", "#205450"];
ctx.lineWidth = 3;
for(var i=0; i<7; i++) {
ctx.beginPath();
ctx.arc( 500, 350, 420-60*i, 0, 2 * Math.PI, false );
if(i==6) {
ctx.fillStyle = "#4DA54D";
ctx.fill();
}
ctx.strokeStyle = strokes[i];
ctx.stroke();
}
// Now do the same for the 24 spokes (Use mathematical formulae)
// this is just from the top of my head, may need some adjustment
angle = 360/25; // you have 24 spokes, so 25 sectors (first and last one overlap or are the same)
for(var j=0; j<24; j++) {
ctx.beginPath();
ctx.moveTo(500, 350);
ctx.lineTo(500+420*Math.sin(angle*j), 350-420*Math.cos(angle*j));
ctx.strokeStyle = "blue";
ctx.stroke();
}
Labels
For printing labels on the dial:
angle = 360/23;
for(var i=0; i<23; i++) {
x = <centerX> + <radius> * Math.sin(angle*i*Math.PI/180) // convert from radian to angle
y = <centerY> - <radius> * Math.cos(angle*i*Math.PI/180)
context.fillText(i+1, x, y);
}

Can I plot HTML5 Canvas x/y points programatically using jQuery with external JSON data?

I've got an HTML5 canvas 'join the dots' type thing going - 2 lines with dots at their angle points - this is fine but I want to plot the X coordinates programatically with external JSON data (pulled from a 'local' server so won't need to be JSONP) - I hope I explain this clearly ...
I'm not trying to convert the JSON data into new DOM elements, but instead I need to apply the data to the actual script which maps the canvas coordinates. Ideally I want to use jQuery for this and my guess is that I will need to parse a JSON object via .getJSON(), but this is where I need some help.
Both X and Y coordinates are currently initiated with hard-coded variables in the canvas script but I want the JSON data to parse into the X variable programatically (the Y co-ords can stay hard coded and work fine for both lines).
Here's a fiddle of what I have so far: http://jsfiddle.net/ByT58/6/
Here's the markup/script for reference - and big thanks in advance for any help!:
HTML:
<div class="canvas-wrap">
<canvas id="myCanvas" width="200" height="115"></canvas>
</div>
Here's how the external JSON would look:
{
"red": {
"r01x": 20,
"r02x": 149,
"r03x": 50
},
"blue": {
"b01x": 80,
"b02x": 179,
"b03x": 20
}
}
JS:
var ctx = document.getElementsByTagName('canvas')[0].getContext('2d');
// set attributes for all circles
var radius = 7;
// set attributes for all lines
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
// set X co-ords for Red
var r01x = 20;
var r02x = 149;
var r03x = 50;
// set X co-ords for Blue
var b01x = 80;
var b02x = 179;
var b03x = 20;
// Set default Y coordinates for both Red and Blue
var y01 = 20;
var y02 = 50;
var y03 = 100;
// RED dots
ctx.beginPath();
ctx.fillStyle = "#E51919";
ctx.arc(r01x, y01, radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = "#E51919";
ctx.arc(r02x, y02, radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = "#E51919";
ctx.arc(r03x, y03, radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
// RED line
ctx.beginPath();
ctx.moveTo(r01x, y01);
ctx.lineTo(r02x, y02);
ctx.lineTo(r03x, y03);
ctx.strokeStyle = "#E51919";
ctx.stroke();
ctx.closePath();
// BLUE dots
ctx.beginPath();
ctx.fillStyle = "#133175";
ctx.arc(b01x, y01, radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = "#133175";
ctx.arc(b02x, y02, radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = "#133175";
ctx.arc(b03x, y03, radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
// BLUE line
ctx.beginPath();
ctx.moveTo(b01x, y01);
ctx.lineTo(b02x, y02);
ctx.lineTo(b03x, y03);
ctx.strokeStyle = "#133175";
ctx.stroke();
ctx.closePath();
If you were to put your JSON data into the form:
{
red: { color: "#E51919", x: [20,149,50] },
blue: { color: "#133175", x: [80,179,20] }
}
Your draw function would look something like (jsFiddle here):
function draw(data) {
var ctx = document.getElementsByTagName('canvas')[0].getContext('2d');
// set attributes for all circles
var radius = 7;
// set attributes for all lines
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
var y = [20,50,100];
for(var key in data) {
var x = data[key].x;
ctx.fillStyle = data[key].color;
for(var i = 0; i < x.length; ++i) {
ctx.beginPath();
ctx.arc(x[i], y[i], radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
}
ctx.beginPath();
ctx.moveTo(x[0], y[0]);
ctx.lineTo(x[1], y[1]);
ctx.lineTo(x[2], y[2]);
ctx.strokeStyle = data[key].color;
ctx.stroke();
ctx.closePath();
}
}
draw({
red: { color: "#E51919", x: [20,149,50] },
blue: { color: "#133175", x: [80,179,20] }
});
Using JQuery to retrieve the JSON data from the server use jQuery.getJSON() or jQuery.ajax()
for example (no error handling...):
$.getJSON('path/data.json', function(data, textStatus, jqXHR) {
console.log(textStatus);
draw(data);
})
.fail(function( jqXHR, textStatus, errorThrown) { console.log(textStatus + " :: " + errorThrown ); });

Categories