canvas教程

Plotting a function graph with JavaScript

字号+ 作者:H5之家 来源:H5之家 2017-06-11 12:07 我要评论( )

Plotting a function graph JavaScript FAQ |JavaScript Numbers FAQ Question: How do I plot a graph of a mathematical function using JavaScript? Answer: To plot a graph of a function on your webpage, use the canvas element, as shown in the ex

Plotting a function graph

JavaScript FAQ | JavaScript Numbers FAQ  

Question: How do I plot a graph of a mathematical function using JavaScript?

Answer: To plot a graph of a function on your webpage, use the canvas element, as shown in the example below. The canvas element is supported in all major browsers: Firefox, Opera, Safari, Google Chrome, and Microsoft Internet Explorer 9 or newer.

Example: Here is a graph of the functions sin x (green) and cos 3x (blue).

The graph has been created using the following JavaScript code: function fun1(x) {return Math.sin(x); } 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 = 40; // 40 pixels from x=0 to x=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 It is safe to call the draw() function after the entire body of the webpage is loaded. The source code of an HTML page containing the canvas element may look like this: <!DOCTYPE html> <html> <head><title>Canvas code example</title> <script type="text/javascript"> // JavaScript source code goes here </script> </head> <body> <canvas></canvas> </body> </html>

Note: If you omit the DOCTYPE element at the beginning of the page, then the graphics might not show up in IE browsers: without the DOCTYPE element, IE may switch to the backward compatibility mode and treat canvas as an unsupported tag.

See also:
• Mathematical functions
• Mathematical constants
• Mathematical and special symbols
• (at open-libraries.com)

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • 在Android中需要通过graphics类来显示2D图形

    在Android中需要通过graphics类来显示2D图形

    2017-04-27 11:00

  • +function 前面的那个加号是什么意思,跟js中的“

    +function 前面的那个加号是什么意思,跟js中的“

    2017-04-25 10:04

  • ArcGIS api fo silverlight学习二(silverlight加载GraphicsLayer)

    ArcGIS api fo silverlight学习二(silverlight加载GraphicsLayer)

    2017-02-05 08:01

  • GraphicsGale(像素动画制作软件)下载v2.4.7绿色汉化版

    GraphicsGale(像素动画制作软件)下载v2.4.7绿色汉化版

    2017-01-10 18:04

网友点评
t