Native js and canvas simulated electrocardiogram code sharing
The html page that simulates electrocardiogram is made using native js+canvas. Since it is packaged and put on github together with the project, it uses the single-page mode of vue.js. In fact, you do not need to use any additional frameworks and styles. You can also complete this demo, now let’s dismantle this project together!
1: Create a canvas on the page. To make the "line" of the electrocardiogram move on our page, canvas is essential. Because the project is relatively simple, the DOM elements on the page have been written so far. The main workload is concentrated in the js part
##
<p class="heartBeat"> <canvas id="can">Canvas画板</canvas> </p>2: Define several variables and assign values. These variables will be needed for calculation during runtime
var can = document.getElementById('can'),//画布对象 pan,//获取2D图像API接口 index = 0,//用来接收setinerval的值 flag = true,//用来控制心电图折线的运行方向 wid = document.body.clientWidth,//获取浏览器宽度 hei = document.body.clientHeight,//获取浏览器高度 x = 0,//心电图的“点”在画布上的x轴坐标,从0开始 y = hei/2;//心电图的“点”在画布上的y轴坐标,从页面y轴居中位置开始3: Initialize the canvas and set various properties for the canvas
function start(){ can.height = hei;//设置画布高度 can.width = wid;//设置画布宽度 pan = can.getContext("2d");//获取2D图像API接口 pan.strokeStyle = "#08b95a";//设置画笔颜色 pan.lineJoin = "round";//设置画笔轨迹基于圆点拼接 pan.lineWidth = 9;//设置画笔粗细 pan.beginPath();//开始一条画笔的路径 pan.moveTo(x,y);//定位我们的“落笔点” index = setInterval(move,1);//让我们的画笔动起来 };As you can see, we have not yet involved the "painting" action here. We just initialized the canvas size so that the canvas fills the screen. At the same time, we defined the color, thickness, pen point and other operations of the brush, and then used the setInterval method. Let the brush keep moving along the route we calculated. If you are not very familiar with the setInterval method, I suggest you take a look at the usage of setInterVal, which will not be described here. Because we want the electrocardiogram to loop infinitely and execute automatically, we encapsulate it here as the start() function, so that when the electrocardiogram moves to the far right of the screen, we re-execute the start() function to make the electrocardiogram infinite. It’s a cycle4. Let the electrocardiogram move! It can be said that the previous steps are not difficult. The real core code is to make our electrocardiogram move and move along the route we want. Now we will make the electrocardiogram really come alive
function move(){ x++;//x轴是始终运动的,所以x一直自增 if(x < 100){ //前100px,我们不希望做垂直运动,让点只沿垂直方向运动即可,所以不做任何操作 }else{ if(x >= wid - 100){ //最后的100px,同样希望心电图只做水平运动,不会上下波动,所以不做任何操作 }else{ //为了让心电图看起来更加逼真,我们希望心电图在运动时每次的波峰和波谷都是随机的,这样更类似于人类的心跳,所以我们给它一个随机值z var z = Math.random()*280; if(y <= z){ //画布的坐标是从左上角开始计算的,也就是最左上角的点的坐标是(0,0),y是当前画笔所在坐标的y轴,假如y小于z,就代表y已经到达波峰位置,准备开始向波谷运动 flag = true } if((hei - y) <= z){ //假如当前画笔在y轴的坐标y距离浏览器底部hei的差值已经小于随机值z,代表当前的画笔已经运行到波谷位置,准备转向波峰位置运动 flag = false } if(flag){ //假如flag为true,代表画笔仍然向波谷位置前进,需要花点功夫理解的是,因为画布左上角的点的坐标是(0,0),所以y的值越大,画笔在y轴的位置越靠近浏览器底部,所以向波谷运动时,y的值是不断增加的,同时为了让波峰波谷更陡峭,我这里设置y += 5, y+=5 }else{ //假如flag为false,表示向波峰运动,y的值是不断减小的 y-=5 } } } if(x == wid){ //当画笔运动到浏览器右侧边缘,停止绘图 pan.closePath(); //清除循环 clearInterval(index); //将index置零,准备下一次循环 index = 0; //重新定位画笔到屏幕左侧上下居中的位置 x = 0; y = hei/2; flag = true; //重新进行下一次心电图的绘制 start(); } //lineTo和stroke函数负责描绘运动轨迹 pan.lineTo(x,y); pan.stroke(); }5: Note, the electrocardiogram can actually be run at this point, but it should be noted that set your body height to 100%, otherwise the canvas may not be able to fill the entire page
html,body{ width: 100%; height: 100%; margin: 0; }Complete project code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模拟心电图</title> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <style> html,body{ width: 100%; height: 100%; margin: 0; } </style> </head> <body> <p id="canvas"> <canvas id="can">Canvas画板</canvas> </p> <script src="js/vue.min.js"></script> <script> var can = document.getElementById('can'), pan, index = 0, flag = true, wid = document.body.clientWidth, hei = document.body.clientHeight, x = 0, y = hei/2; start(); function start(){ can.height = hei; can.width = wid; pan = can.getContext("2d");//获取2D图像API接口 pan.strokeStyle = "#08b95a";//设置画笔颜色 pan.lineJoin = "round";//设置画笔轨迹基于圆点拼接 pan.lineWidth = 9;//设置画笔粗细 pan.beginPath(); pan.moveTo(x,y); index = setInterval(move,1); }; function move(){ x++; if(x < 100){ }else{ if(x >= wid - 100){ }else{ var z = Math.random()*280; if(y <= z){ flag = true } if((hei - y) <= z){ flag = false } if(flag){ y+=5 }else{ y-=5 } } } if(x == wid){ pan.closePath(); clearInterval(index); index = 0; x = 0; y = hei/2; flag = true; start(); } pan.lineTo(x,y); pan.stroke(); } /* */ </script> </body> </html>Related recommendations:
Canvas achieves dazzling Particle motion effect
canvas polygon drawing example
html2 canvas implementation browser screenshot
The above is the detailed content of Native js and canvas simulated electrocardiogram code sharing. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use