App inventor 2 en español
Cómo programar los teléfonos móviles con Android.
Curso de App inventor 2 en español - Juan Antonio Villalpando
-- Tutorial de iniciación de App Inventor 2 en español --
Volver al índice del tutorial
___________________________
169M.- Funciones gráficas con JavaScript.
p169M_javascript_funciones.aia
- Vamos a dibujar la gráfica de dos funciones en la pantalla.
- Las funciones son:
function fun1(x) {return -3*x+2; }
function fun2(x) {return Math.cos(3*x);}
- El código está ligeramente adaptado de esta web:
http://www.javascripter.net/faq/plotafunctiongraph.htm
_________________
- Diseño.
- Subimos el archivo dibujar.htm
- Orientación de la Pantalla: Horizontal
- El Deslizador tiene valores de 10 a 100.
- En la Screen1 he desmarcado TitleVisible.
_________________
- Bloques.
_________________
- Archivo dibujar.htm
dibujar.htm |
<!DOCTYPE html>
<html>
<head><title></title>
<script type="text/javascript">
datos = window.AppInventor.getWebViewString();
function fun1(x) {return -3*x+2; }
function fun2(x) {return Math.cos(3*x);}
function draw() {
var canvas = document.getElementById("canvas");
if (null==canvas || !canvas.getContext) return;
var axes={}, ctx=canvas.getContext("2d");
axes.x0 = .5 + .5*canvas.width; // x0 pixels from left to x=0
axes.y0 = .5 + .5*canvas.height; // y0 pixels from top to y=0
axes.scale = datos; // altura en pixel del 1
axes.doNegativeX = true;
showAxes(ctx,axes);
funGraph(ctx,axes,fun1,"rgb(11,153,11)",1);
funGraph(ctx,axes,fun2,"rgb(66,44,255)",2);
}
function funGraph (ctx,axes,func,color,thick) {
var xx, yy, dx=4, x0=axes.x0, y0=axes.y0, scale=axes.scale;
var iMax = Math.round((ctx.canvas.width-x0)/dx);
var iMin = axes.doNegativeX ? Math.round(-x0/dx) : 0;
ctx.beginPath();
ctx.lineWidth = thick;
ctx.strokeStyle = color;
for (var i=iMin;i<=iMax;i++) {
xx = dx*i; yy = scale*func(xx/scale);
if (i==iMin) ctx.moveTo(x0+xx,y0-yy);
else ctx.lineTo(x0+xx,y0-yy);
}
ctx.stroke();
}
function showAxes(ctx,axes) {
var x0=axes.x0, w=ctx.canvas.width;
var y0=axes.y0, h=ctx.canvas.height;
var xmin = axes.doNegativeX ? 0 : x0;
ctx.beginPath();
ctx.strokeStyle = "rgb(128,128,128)";
ctx.moveTo(xmin,y0); ctx.lineTo(w,y0); // X axis
ctx.moveTo(x0,0); ctx.lineTo(x0,h); // Y axis
ctx.stroke();
}
// Juan A. Villalpando - KIO4.COM
</script>
</head>
<body onload="draw()">
<canvas id="canvas" width="500" height="250"></canvas>
</body>
</html>
|
_________________
- Comentarios.
- El tamaño de la pantalla se establece en
<canvas id="canvas" width="500" height="250"></canvas>
- La altura del y = 1 se establece en
axes.scale = datos; // altura en pixel del 1
- Es decir, si ponemos datos a 40, significa que 40 pixeles será la altura de y = 1
- Este dato cambia según movamos el Deslizador.
- Al mover el Deslizador cambiará el Dato y el valor de y = 1 tendrá más altura de pixel.
_________________
- Propuesta.
- Envía la función desde App Inventor.
__________________________________
|