Monday, December 8, 2014

Final Lesson: Function Plotter in detail

1) First you need a text field for your equation and a plot button, and of course define your canvas

2) Javascript has this great method to evaluate an expression (for other compiled langauge, that is quite hard to do)

var x = 10;
var expression = "2*x+3"
alert(eval(expression))
See it in action.

x= Expression:
Give yourself a function to evaluate
function func(x) {
  var eq=document.getElementById("func").value;
  var result= eval("x="+x+";"+eq);
  return result; 
}

3) Figure out your coordinates

The function plotter has (-5,-5) to (5,5) in range. This is called your world coordinate.

Your plotting canvas is going from (0,0) to (500,500) in range. That is called the view coordinate.

You will need to do some transformation.

var  xvl = 0;
var  yvl = 0; // viewport is the Canvas

var  xvu = 500
var  yvu = 500

var  xwl = -5
var  ywl = -5
var  xwu = 5
var  ywu = 5

var  Sx = (xvu - xvl) / (xwu - xwl);
var  Sy = (yvu - yvl) / (ywu - ywl);
var  Tx = (xwu * xvl - xwl * xvu) / (xwu - xwl);
var  Ty = (ywu * yvl - ywl * yvu) / (ywu - ywl);
4) Give yourself a convenience function to plot line
function plotLine2D(context, x1, y1, x2, y2, c) {

  t_x1 = Sx * x1 + Tx;
  t_y1 = 500- (Sy * y1 + Ty);
  t_x2 = Sx * x2 + Tx;
  t_y2 = 500 -(Sy * y2 + Ty);


  if (c=="blue")  context.strokeStyle = "#00f"
  if (c=="black")  context.strokeStyle = "#000"

  context.lineWidth   = 2;

  context.beginPath();

  context.moveTo(t_x1, t_y1); 
  context.lineTo(t_x2, t_y2);

  context.stroke();
  context.closePath();

 }
5) Give yourself another convenience function to clear screen (with a black border)
function cls(context) {
context.fillStyle   = '#fff';
context.strokeStyle = '#f00';

context.beginPath();
context.moveTo(0,0);
context.lineTo(0,500);
context.lineTo(500,500);
context.lineTo(500,0);
context.fill();

context.closePath();
}
Now, all you have to do is

1) Plot axes:

  var  xmin = xwl;
  var  ymin = ywl;
  var  xmax = xwu;
  var  ymax = ywu;

  plotLine2D(context, xmin, 0, xmax, 0, "black"); // x-axis;
  plotLine2D(context, 0, ymin, 0, ymax, "black"); // y-axis;
2) Plot little ticks
  var tick = 1

  for (x = xmin; x <= xmax; x += tick) {
   plotLine2D(context,x, -0.1, x, 0.1, "black");
  }
  for (y = ymin; y <= ymax; y += tick) {
   plotLine2D(context,-0.1, y, 0.1, y, "black");
  }
3) do a loop to plot 100 little segments.

  var dx = (xmax - xmin) / 100;
  var x, y, oldx, oldy;
 
  var hasError = false
  x = xmin;
  y = func(x);

  oldx = x;
  oldy = y;
  while (x <= xmax) {
   x = x + dx;
   y = func(x);
 
   plotLine2D(context, oldx, oldy, x, y, "blue");
   oldx = x;
   oldy = y;

  }// while

Ok just copy everything here. View Source look for [BEGIN]
f(x) = (For trig functions, use Math.sin, Math.cos, Math.tan)
Your browser does not support the canvas element.

This is my first Android App but unfortunately not many is willing to pay just $1. (Too many people made free ones that are better)

Get it on Google Play

Monday, December 1, 2014

Lesson 8: HTML5 canvas

HTML is originally intended for simple text, and drawing, audio and video was originally achieved by browser plugins such as Flash and Java Applets.. until HTML5 (about 2008). Super duper slide show here: http://slides.html5rocks.com/#landing-slide. I actually only used just some of its features. Note: not all browsers support all features.

This is a great link for experimenting with it: http://www.w3schools.com/html/html5_canvas.asp.

First, define a canvas, with an apology note for old browsers.

<canvas id="myCanvas1" width="200" height="200" style="border:1px solid blue;">
Sorry, your browser does not support canvas
</canvas>

Then we need javascript to draw. You will need to get the "context". Then call the methods within the context to draw lines, text, images. This tells you all the things you can do with it: http://www.w3schools.com/tags/ref_canvas.asp

This is an example to draw line.

var c = document.getElementById("myCanvas1");
var ctx = c.getContext("2d");
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.closePath();
ctx.stroke();
from (0,0) - (200,100)

With specific width and color

var c = document.getElementById("myCanvas1");
var ctx = c.getContext("2d");

ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.lineWidth = 10;
ctx.strokeStyle = '#ff0000';
ctx.closePath();

ctx.stroke();

with specific width and style (color)

Sorry, your browser does not support canvas

Draw a filled rectangle

var c = document.getElementById("myCanvas1");
var ctx = c.getContext("2d");

ctx.fillStyle = 'green';
ctx.fillRect(30,30,100,100);

Draw Arc (Cricle). x, y, radius, start angle, end angle (in radians). (Radian is an alternative to degree measure. There are 2π radian in 360°)

var c=document.getElementById("myCanvas1");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(100,75,50,0,2*Math.PI);
ctx.stroke();

var c=document.getElementById("myCanvas1");
var ctx=c.getContext("2d");

ctx.font="20px Georgia";
ctx.rotate(20*Math.PI/180)
ctx.fillText("Hello World!",10,50);

Now I showed you almost everything you need to do the function plotter.

Tuesday, November 25, 2014

Javascript objects and array of objects

Programming language is actually designed to make life easier for developers... and one way is to group related things into objects. Object-oriented programming (OOP) is a big topic in computer science. Can javascript do OOP? The answer is... yes, but this isn't quite the same as other languages. I suggest learning OOP in C++ or Java.

But the basic idea of an object is simple... you define things within.. known as properties.

Like a TV has its channel buttons and volume controls. Like a car has a make, model and color. Details of how a TV or a car works is staying inside the object.

For example: (the syntax is braces)

var car = {type:"Fiat", model:500, color:"white"};
For details in here: http://www.w3schools.com/js/js_objects.asp.

You access properties with a dot. like alert( car.color ) will give you white.

Push into an array

You can define all the elements in an array with 1 line. (The syntax is square bracket). A blank array is just [].
var prime = [2,3,5,7,11]
You access with an index that starts with 0, like prime[0] gives you 2, prime[2] gives you 5.

Another thing about arrays in Javascript. You can keep adding to it with a "push". In other languages it is not so easy to attach new item to an array. Javascript can do this because of its dynamic nature.

Example: add another prime number onto your list:

prime.push(13);

(You win a prize if you can tell me why there are infinitely many primes)

And you can have an array of objects.

The following works exactly the same as the code in Lesson 7. So instead of 2 arrays, I have object called planet, and I can easily define more things for each planet.

<script>
var planet;

var planets = [];


planet = { name: 'Mercury',
                img: 'http://upload.wikimedia.org/wikipedia/commons/thumb/3/30/Mercury_in_color_-_Prockter07_centered.jpg/270px-Mercury_in_color_-_Prockter07_centered.jpg'}
planets.push(planet);

planet = { name: 'Venus',
           img: 'http://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Venus_globe.jpg/250px-Venus_globe.jpg'}

planets.push(planet);

planet = { name: 'Earth',
           img: 'http://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/Earth_Eastern_Hemisphere.jpg/300px-Earth_Eastern_Hemisphere.jpg'}

planets.push(planet);

planet = { name: 'Mars',
           img: 'http://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Water_ice_clouds_hanging_above_Tharsis_PIA02653_black_background.jpg/250px-Water_ice_clouds_hanging_above_Tharsis_PIA02653_black_background.jpg'}

planets.push(planet);

planet = { name: 'Jupiter',
           img: 'http://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Jupiter_by_Cassini-Huygens.jpg/260px-Jupiter_by_Cassini-Huygens.jpg'}

planets.push(planet);

planet = { name: 'Saturn',
           img: 'http://upload.wikimedia.org/wikipedia/commons/thumb/2/25/Saturn_PIA06077.jpg/280px-Saturn_PIA06077.jpg'}

planets.push(planet);

planet = { name: 'Uranus',
           img: 'http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/Uranus2.jpg/240px-Uranus2.jpg'}

planets.push(planet);

planet = { name: 'Neptune',
           img: 'http://upload.wikimedia.org/wikipedia/commons/thumb/0/06/Neptune.jpg/240px-Neptune.jpg'}

planets.push(planet);

var i=2; // show we show Earth first, as Earth is planents[2], the third planet from the sun.

function showPlanet(i) {

  document.getElementById("planet").innerHTML="<img src="+planets[i].img+" width=200 height=200><br>"+planets[i].name;
}
function doPrev() {
  if (i==0) {
    i=7;
//   alert("go to last planet")

  }else {
    i--;
  }
  showPlanet(i);
}

function doNext() {
  if (i==7) {
   i= 0;
//   alert("back to beginning")
  }
  else {
   i++;
  }
  showPlanet(i);
}


</script>
<table><tr><td>
<input type="button" value="<" onclick="doPrev()">
</d>
<td>
<div id="planet"></div>
</td>
<td>
<input type="button" value=">" onclick="doNext()">
</td>
</tr></table>
<script>

showPlanet(i); // show Earth first
</script>

Friday, November 21, 2014

Lesson 7: More on Array; then Intro to Stylesheet

I want to do last example of array.

Do you think you can do this planet display? I found all the images from wikipedia.

To make this happen, naturally you will need array to hold the image and names. Then you assign a function to the buttons to change the index and then do something with it!

Styles

Styles can be hard coded, but generally not a very good practice

<h1 style="font-size:60px;font-family:Tahoma;color:red">big header</h1>

Better practice is to define overall styles and add named styles.

Stylesheet

Stylesheet is the real power of modern web site programming... Programmers can focus on the logic and designers can focus on styles. Stylesheets usually lives in its own CSS file. <link rel="stylesheet" type="text/css" href="mystyle.css">
Javascript files usually lives in its own file too: <script type="text/javascript" src="somefile.js"></script>
<!--
CSS is real powerful.
You are defining your own style. It uses "selector".
Usually it is in its own file.

# is for a specific id
. is for class

-->



<head>
<style>
h1 {
    font-size: 60px;
    font-family: Tahoma;
    color: red;
}

#para1 {
    text-align: center;
    color: green;
}

.mystyle {
    font-family: Times;
    color: blue;
}

</style>
</head>

<body>

<h1>big header</h1>

some unaffected text

<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the para1 style.</p>

<div class="mystyle">
I am some blue thing
</p>

</body>

big header

some unaffected text

Hello World!

This paragraph is not affected by the para1 style.

I am some blue thing
I'd like you to take a look at some of these here: http://www.w3schools.com/css/css_examples.asp.

Take a special look at

Magic time


An useful example of show/hide: validation messages. You can put all your error messages in, but hidden initially, and set style=block to display it in your validation routine.

Enter some positive number please:

Tuesday, November 18, 2014

Review: What's the div again?

So a div tag is a division block... basically just a named spot on your html form.

In a traditional programming language I can send things to the console but we are programming web page here, so to demonstrate certain piece of code creating certain output, I use a div tag to contain the result. We can use the innerHTML method to put new values in.

We also put any editable items on a <form> so we can reference it using document.form name.field name.value to get its value.
We also put a button and set its onClick property so that a line (usually a function) gets called when you click it and you determine what you want to do in that function.

Example: Watch happens when you hit the button below. Whatever you put on the text field will be inserted into the DIV, and the original value will be gone.

<form name="form6c">
Enter something, it will be inserted below: <input type="text" name="something" value="hello my friend"/>
<input type="button" value="click me" onclick="document.getElementById('somediv').innerHTML = document.form6c.something.value"/>
</form>
--- somediv start ---<br>
<div id="somediv">
This is my original value
</div>
--- somediv end ---<br>
Enter something, it will be inserted below:
--- somediv start ---
This is my original value
--- somediv end ---

Friday, November 14, 2014

Lesson 6: More on loops

Since loops are so important in programming let's do a few more examples.

Array is variable to store multiple values, referenced by an index. It is very useful to hold data that you can go through each. In Javascript (and C, C++, Java), index starts at 0. Example:

var weekDays = ["Monday","Tuesday","Wednesday","Thursday","Friday"];
alert(weekDays[0]);
alert(weekDays[1]);
alert(weekDays[2]);

// or do this in a loop
for (var i=0; i < weekDays.length; i++) {
  alert(weekDays[i])
}
Now, let's do something more useful. How about I give you a list of number and you tell me which one is largest. In real life, data may be read from a file, but sorry, javascript in browser can't do that.

// Find the largest number
var data = [20,12,15,22,44,98,2]
var largest = 0;
for (var i=0; i < data.length; i++) {
  var n = Number(data[i])
  if (n > largest) {
    largest = n;
  }
}
alert("largest: "+largest);

Now that was hard coded list.

How about you enter from a input text box. separate by comma. The split method lets you easily do that.

  var greetings="Hello how are you"
  var splitted = greetings.split(" ");
  for (var i=0; i < splitted.length; i++) {
     alert(splitted[i]);
  }
Enter a list of numbers (separated by comma):
Your turn: how about you find the smallest number on a list?

Double for loop

You can do loop within a loop. Behold, the multiplication table you spent so much time to remember:

function createmulttable() {
var s= ""
for (var i=1; i < 10; i++) {
  for (var j=1; j < 10; j++) {
    var p = i*j;
    if (p < 10) s = s+" ";
    s = s + i*j+" ";
 }
 s = s+"<br>" // line break
}
document.getElementById("multtable").innerHTML = "<pre>"+s+"</pre>";
}
Make sure you have this div defined:
<div id="multtable"></div>

Sign up Sheet - demonstrating breaking down problem to small ones (and writing functions)

Enter lines:

Monday, November 10, 2014

Lesson 5: condtions and loops

Table without borders:
See http://www.w3schools.com/html/tryit.asp?filename=tryhtml_table_collapse

It takes us to lesson 5 to begin introducing the essence of programming... loops and conditions. They are fundamental in programming. Without these there is only very little things we can do and with loops you can really tell your computer to tirelessly do some work.

Javascript knows how to compare things (especially numbers), and you can combine conditions with logical operators: AND, OR and NOT. See details here: http://www.w3schools.com/js/js_comparisons.asp.

Most of the (rather unusual) syntax is borrowed from Java (which borrowed from C). Especially note there are two equal signs for equal. One equal sign is for assignment, such as var x=10;

Comparing Operators

OperatorDescription
==Equals
>=Greater Than Or Equals
<=Less Than Or Equals
>Greater Than
<Less Than
!=Not

Logical Operators

OperatorDescription
&&And
||Or
!Not

Examples

Enter your age:
Enter money amount: (shows blue if zero or positive, or red if negative)

Loops - this is where real power of programming comes from. It will do your steps as long as your specified condition holds.

The while loop.

while (condition) {
  // statements;
}
Remember to specify change of condition within the block or you get infinite loop.

Example:


var i=1;
while (i < 5) {
  alert("hi "+i);
  i = i + 1 // (or i++)
}

There is also the do-while (which I have not ever seen many times in 20 years of professional programming career). The block will be run at least once. The block within the while loop above may not run at all.

var i=1;
do {
  alert("hi "+i);
  i = i + 1;
}
while (i < 5)
Now try change the condition to (i > 100) (which is false)

The pattern of while loop with a init statement, condition, and last increment statement is used so often that a short-cut is made: the for-loop. It has 2 semi-colons in the form: for (init statement; condition; increment statement)

The following is exactly the same as the while loop above:

for (var i=1; i < 5; i++) {
  alert("hi "+i);
}

The for-loop is especially useful to "loop through" a list of items.

Now with loops you can really tell your program to do work.

Punishment line:
How many times?

Array

Another powerful element of programming is the array. It is one name, with an index to represent a table, and index starts with 0.

// number of students attended class so far, sad isn't it:
var students = [4,4,2,1]
var sum = 0
for (var i=0; i < students.length; i++) {
   sum = sum + students[i];
}
var average = sum/students.length;
alert("average:"+average)

Now, let's say you have a little function f(x) = x + 3.

Can you write a program to fill up the following:

xf(x)
-3 
-2 
-1 
0 
1 
2 
3 
We are almost ready to do the function plotter!

One of the greatest mathematicians of all times is Carl Gauss. There was a story about he had a elementary school teacher who wants to keep students all day by telling them to add from 1 to 100. Can you help by writing a little program?

Perhaps you can amaze your friends if you can prove: