search
HomeWeb Front-endH5 Tutorialcanvas draws rectangular coordinate system

canvasDrawing a rectangular coordinate system

March 17, 2017

Using canvas to draw a rectangular coordinate system is actually quite simple, as long as the origin (0, 0) point, it can also be other points, as long as you know that it is the origin! Once you know the origin, just draw two straight lines in the direction of the X-axis and the Y-axis (the X-axis and the Y-axis are also relative, this purely depends on personal preference and actual needs).

Without further ado, let’s just look at the code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>canvas画直角坐标系和柱状图</title>
    </head>
    <body>
        <h1 id="canvas画直角坐标系及柱状图">canvas画直角坐标系及柱状图</h1>
        <canvas id="canvas" width="600" height="400">如果您只看到了这句话,那么您的浏览器该升级换代了!</canvas>
             <!--canvas的宽高即可以设置成行内样式,也可以通过Js设置,不过建议设置成行内样式-->
        <script src="js/drawChart.js" type="text/javascript" charset="utf-8"></script>
        <!--为了表现与样式分离同时为了页面简洁,引入一个外部js文件-->
        <script type="text/javascript">
            var canvas=document.getElementById("canvas");
            var cxt = canvas.getContext("2d");
            //通过id获取canvas画布,并获得cxt画笔,canvas目前只支持2d效果,所以“2d”不能省;
              
            var arr = [16,15,20,21]//利用数组模拟柱状图的数据
            Coordinate(50,350);//自己写的一个直角坐标系
            ColumnChart1(50,350,arr);    //一个简单的柱状图函数     
            /*为了有个简单的动画效果,canvas绘制完成以后先将它隐藏,然后用jQuery的slideDown()方法淡入显示*/
            $("#canvas").hide();
            $("#canvas").slideDown(1000);    
        </script>
    </body>
</html>

Then there is the drawing method of the rectangular coordinate system (if the master sees that the functions are more complete and the code size can be more streamlined, please feel free to enlighten me. , thank you):

function Coordinate(x,y){
        //x为横坐标起点,Y为纵坐标起点
              var originX = x;
               var originY = y;
             //设置原点的那个文字的样式,并绘制出来
               cxt.font = "2rem 微软雅黑";
               cxt.fillText("0",originX-10,originY+15);//此处-10和+15是为了调整字的位置

              cxt.strokeStyle = "black";//设置坐标系X轴Y轴的颜色,绘制线条用strockeStyle属性,绘制填充色块用fillStyle属性;
             cxt.lineWidth = 3;//设置线条粗细,这里为了方便看设置了3个像素,可以根据情况自行调整
           //开始绘制Y轴
     cxt.beginPath();//开启路径
             cxt.moveTo(originX,originY);//x轴与y轴的起点位置
             cxt.lineTo(originX,originY-320);//轴的终点位置,即X大小不变,只是改变了Y点位置(根据实际情况做调整);
             cxt.stroke();//将这条线绘制出来
          //画小箭头
           cxt.moveTo(originX,originY-320);//小箭头起点位置即为Y轴终点位置
            cxt.lineTo(originX+3,originY-310);//originX+3和originY-310是设置小箭头的终点位置,小箭头的大小和尖锐程度请自行摸索
            cxt.stroke();
            cxt.moveTo(originX,originY-320);
            cxt.lineTo(originX-3,originY-310);
           cxt.stroke();
          //画横坐标
     //绘制X轴和Y轴相似
          cxt.moveTo(originX,originY);
          cxt.lineTo(originX+450,originY);
          cxt.stroke();
         //画小箭头
         cxt.moveTo(originX+450,originY);
         cxt.lineTo(originX+440,originY-3);
        cxt.stroke();
         cxt.moveTo(originX+450,originY);
         cxt.lineTo(originX+440,originY+3);
         cxt.stroke();
         cxt.fillText("Y轴",originX-5,originY-325)
     }

Then there is the method of drawing the histogram:

function ColumnChart1(x,y,arr){
        //绘制之前先清空原有的柱状图所占区域
        cxt.clearRect(x,y,500,0);
        var arrColor = ["red","yellow","blue","purple","green","mauve"];//为了使每个柱子的颜色不一样,如果可以尽量用#******或rgb()方法设置颜色,因为我这样直接用单词有些浏览器对个别颜色不识别(头疼的IE)
        //请务必保持x,y值与坐标系的x,y值相同
        this.arr= arr;
        for (var i=0;i<arr.length;i++ ) {//for循环用来遍历数组内数据
                if(i==0){
                    var    originX = x+40;
                    var originY = y-1;
                }else{
                    var originX = i*70+80;
                    var originY = y-1;
                }
                cxt.beginPath();
                cxt.strokeStyle = arrColor[i];//设置线条颜色
                cxt.lineWidth = 20;//这里为了方便直接将线条的宽度设置为20,这样就可以模拟柱子
                cxt.moveTo(originX+(i+1)*20,originY);//柱子的顶点位置,这里因为数组内数字小,所以都乘十了,这样有利于小数字的表现
                cxt.lineTo(originX+(i+1)*20,originY-(arr[i]*10));//调整每根柱子的间距;
                cxt.stroke();    
                cxt.font = "20px 宋体"
                cxt.fillText(arr[i],originX+(i+1)*20-10,originY-(arr[i]*10+3));
                //文字的绘制
                cxt.font = "13px 宋体"
                cxt.fillText("第"+(i+1)+"季度业绩",originX+(i+1)*20-35,originY+20)
            }
        }

If you still want the chart to look more beautiful, you can use the shadowColor, shadowOffsetX, shadowOffsetY, etc. provided by canvas. Related properties set the shadow.

At the same time, draw an ellipse with a slightly different color than the column with the vertex of the column as the center.

The above is the detailed content of canvas draws rectangular coordinate system. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

Is h5 same as HTML5?Is h5 same as HTML5?Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

What is the function of H5?What is the function of H5?Apr 07, 2025 am 12:10 AM

H5, or HTML5, is the fifth version of HTML. It provides developers with a stronger tool set, making it easier to create complex web applications. The core functions of H5 include: 1) elements that allow drawing graphics and animations on web pages; 2) semantic tags such as, etc. to make the web page structure clear and conducive to SEO optimization; 3) new APIs such as GeolocationAPI support location-based services; 4) Cross-browser compatibility needs to be ensured through compatibility testing and Polyfill library.

How to do h5 linkHow to do h5 linkApr 06, 2025 pm 12:39 PM

How to create an H5 link? Determine the link target: Get the URL of the H5 page or application. Create HTML anchors: Use the <a> tag to create an anchor and specify the link target URL. Set link properties (optional): Set target, title, and onclick properties as needed. Add to webpage: Add HTML anchor code to the webpage where you want the link to appear.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

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),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.