Home > Web Front-end > H5 Tutorial > Super strategy for drawing rectangles using HTML5 Canvas API_html5 tutorial tips

Super strategy for drawing rectangles using HTML5 Canvas API_html5 tutorial tips

WBOY
Release: 2016-05-16 15:45:35
Original
1921 people have browsed it

Use closePath() to close the shape
First we draw a rectangle using the most common method.

JavaScript CodeCopy content to clipboard
  1.   
  2. "en">   
  3.   
  4.     "UTF-8">   
  5.        
  6.   
  7.   
  8.   
  9. "zh">   
  10.   
  11.     "UTF-8">   
  12.     绘制矩形   
  13.   
  14.   
  15. "canvas-warp">   
  16.     "canvas" style="border: 1px solid #aaaaaa; display: block; margin: 50px auto;">   
  17.         你的浏览器居然不支持Canvas?!赶快换一个吧!!   
  18.        
  
  •   
  • <script>   </span></li> <li> <span>    window.onload = </span><span class="keyword">function</span><span>(){   </span> </li> <li class="alt"> <span>        </span><span class="keyword">var</span><span> canvas = document.getElementById(</span><span class="string">"canvas"</span><span>);   </span> </li> <li><span>        canvas.width = 800;   </span></li> <li class="alt"><span>        canvas.height = 600;   </span></li> <li> <span>        </span><span class="keyword">var</span><span> context = canvas.getContext(</span><span class="string">"2d"</span><span>);   </span> </li> <li class="alt"><span>  </span></li> <li><span>        context.beginPath();   </span></li> <li class="alt"><span>        context.moveTo(150,50);   </span></li> <li><span>        context.lineTo(650,50);   </span></li> <li class="alt"><span>        context.lineTo(650,550);   </span></li> <li><span>        context.lineTo(150,550);   </span></li> <li class="alt"> <span>        context.lineTo(150,50);     </span><span class="comment">//绘制最后一笔使图像闭合 </span><span>  </span> </li> <li><span>        context.lineWidth = 5;   </span></li> <li class="alt"> <span>        context.strokeStyle = </span><span class="string">"black"</span><span>;   </span> </li> <li><span>        context.stroke();   </span></li> <li class="alt"><span>  </span></li> <li><span>    }   </span></li> <li class="alt"><span></script>   
  •   
  •   
  •   
  •   
  • Run result:
    2016321105129852.jpg (850×500)

    At first glance, there is nothing wrong with it, but children's shoes with good eyesight have discovered that there is a problem when the last stroke is closed, resulting in a gap in the upper left corner. This situation is caused by setting lineWidth. If the default is 1 stroke, there will be no problem. But the larger the strokes and the wider the lines, the more obvious this gap will be. So how to avoid this situation?
    The title has already spoiled it, use clothPath() to close the shape.

    JavaScript CodeCopy content to clipboard
    1. "zh">
    2. "UTF-8">
    3. Draw a rectangle
    4. "canvas-warp">
    5. "canvas" style="border: 1px solid #aaaaaa; display: block; margin: 50px auto ;">
    6. Your browser doesn’t support Canvas? ! Change it quickly! !
  • <script> </span></li> <li class="alt"> <span> window.onload = </span><span class="keyword">function</span><span>(){ </span> </li> <li> <span> </span><span class="keyword">var</span><span> canvas = document.getElementById(</span><span class="string">"canvas"</span><span>); </span> </li> <li class="alt"><span> canvas.width = 800; </span></li> <li><span> canvas.height = 600; </span></li> <li class="alt"> <span> </span><span class="keyword">var</span><span> context = canvas.getContext(</span><span class="string">"2d"</span><span>); </span> </li> <li><span> </span></li> <li class="alt"><span> context.beginPath(); </span></li> <li><span> context.moveTo(150,50); </span></li> <li class="alt"><span> context.lineTo(650,50); </span></li> <li><span> context.lineTo(650,550); </span></li> <li class="alt"><span> context.lineTo(150,550); </span></li> <li> <span> context.lineTo(150,50); </span><span class="comment">//You don’t need to draw the last stroke </span><span> </span> </li> <li class="alt"> <span> context.closePath(); </span><span class="comment">//Use closePath() to close the graphic </span><span> </span> </li> <li><span> </span></li> <li class="alt"><span> context.lineWidth = 5; </span></li> <li> <span> context.strokeStyle = </span><span class="string">"black"</span><span>; </span> </li> <li class="alt"><span> context.stroke(); </span></li> <li><span> </span></li> <li class="alt"><span> } </span></li> <li><span></script>
  • Run result:
    2016321105204703.jpg (850×500)

    In this example, combined with the explanation in the previous lesson, we know that when drawing a path, we need to wrap the planned path with beginPath() and closePath(). Of course, you don't need to draw the last stroke, just use closePath() directly, and it will automatically close it for you. (So ​​if you don’t want to draw a closed shape, you can’t use closePath())

    Color the rectangle
    Here we will introduce a method fill() that is equally important as stroke(). Just like the original stroke, before filling, we must first use the fillStyle attribute to select the color to be filled.
    For example, if we want to color the rectangle above yellow, we can write it like this.

    JavaScript CodeCopy content to clipboard
    1.   
    2. "zh">   
    3.   
    4.     "UTF-8">   
    5.     绘制矩形   
    6.   
    7.   
    8. "canvas-warp">   
    9.     "canvas" style="border: 1px solid #aaaaaa; display: block; margin: 50px auto;">   
    10.         你的浏览器居然不支持Canvas?!赶快换一个吧!!   
    11.        
      
  •   
  • <script>   </span></li> <li class="alt"> <span>    window.onload = </span><span class="keyword">function</span><span>(){   </span> </li> <li> <span>        </span><span class="keyword">var</span><span> canvas = document.getElementById(</span><span class="string">"canvas"</span><span>);   </span> </li> <li class="alt"><span>        canvas.width = 800;   </span></li> <li><span>        canvas.height = 600;   </span></li> <li class="alt"> <span>        </span><span class="keyword">var</span><span> context = canvas.getContext(</span><span class="string">"2d"</span><span>);   </span> </li> <li><span>  </span></li> <li class="alt"><span>        context.beginPath();   </span></li> <li><span>        context.moveTo(150,50);   </span></li> <li class="alt"><span>        context.lineTo(650,50);   </span></li> <li><span>        context.lineTo(650,550);   </span></li> <li class="alt"><span>        context.lineTo(150,550);   </span></li> <li> <span>        context.lineTo(150,50);     </span><span class="comment">//最后一笔可以不画 </span><span>  </span> </li> <li class="alt"> <span>        context.closePath();        </span><span class="comment">//使用closePath()闭合图形 </span><span>  </span> </li> <li><span>  </span></li> <li class="alt"> <span>        context.fillStyle = </span><span class="string">"yellow"</span><span>;   </span><span class="comment">//选择油漆桶的颜色 </span><span>  </span> </li> <li><span>        context.lineWidth = 5;   </span></li> <li class="alt"> <span>        context.strokeStyle = </span><span class="string">"black"</span><span>;   </span> </li> <li><span>  </span></li> <li class="alt"> <span>        context.fill();                 </span><span class="comment">//确定填充 </span><span>  </span> </li> <li><span>        context.stroke();   </span></li> <li class="alt"><span>  </span></li> <li><span>    }   </span></li> <li class="alt"><span></script>   
  •   
  •   
  •   
  •   
  •   
  • Run result:
    2016321105516457.jpg (850×500)

    What needs to be noted here is a good coding practice. Because as mentioned before, Canvas is state-based drawing, and drawing is determined only when stroke() and fill() are called. So we're going to put these two lines of code at the end, and the rest of the state setting code before them, to separate the state setting from the code that determines the draw. Improve code readability.


    Encapsulated drawing method
    You must have discovered that drawing a rectangle actually involves four strokes like this. Every time we use this stupid method to draw a rectangle, we have to draw these four strokes. How much trouble if we have to spend 10 rectangles? 100? 1,000? If written like this, the code will be bloated and the reusability will be very low. Here, we can use JavaScript to encapsulate these methods. We know that a rectangle can be uniquely determined by the coordinates of its upper left corner and its length and width.
    JavaScript Function
    Here we introduce JavaScript functions. If you have basic knowledge, you can skip this section and go directly to the following sections.
    JavaScript and ActionScript language function declaration calls are the simplest among programming languages.
    The role of function
    The role of function is to write code once and then reuse this code repeatedly. For example: we want to complete the function of multiple sets of sums.

    JavaScript CodeCopy content to clipboard
    1. var sum;
    2. sum = 3 2;
    3. alert(sum);
    4. sum=7 8 ;
    5. alert(sum);
    6. .... //Repeat two lines of code  

    If you want to implement the sum of 8 groups of numbers, you will need 16 lines of code. The more you implement, the more lines of code you will need. Therefore, we can put the code block that performs a specific function into a function and call this function directly, saving the trouble of repeatedly entering a large amount of code.
    Use functions to complete:

    JavaScript CodeCopy content to clipboard
    1. function add2(a,b){
    2. sum = a b;
    3. alert(sum);
    4. } // You only need to write it once
    5. add2(3,2);
    6. add2(7,8);
    7. .... //Just call the function  

    Define function
    How to define a function? Take a look at the format below:

    JavaScript CodeCopy content to clipboard
    1. function Function name ( )
    2. {
    3. Function body;
    4. }

    function is the keyword that defines a function, "function name" is the name you give the function, and "function body" is replaced with the code that completes the specific function.
    Function call
    After a function is defined, it cannot be executed automatically. You need to call it and write the function name directly in the required position. There are generally two ways:

    Case 1: Called within the <script> tag. </p> <div class="codeText"> <div class="codeHead"> <span class="lantxt">JavaScript Code</span><span style="CURSOR: pointer" class="copyCodeText" onclick="copyIdText('code_6911')">Copy content to clipboard</span> </div> <div id="code_6911"> <ol class="dp-c"> <li class="alt"><span><span><script> </span></span></li> <li> <span></span><span class="keyword">function</span><span> tcon() </span> </li> <li class="alt"><span>{ </span></li> <li> <span> alert(</span><span class="string">"Congratulations on learning function calling!"</span><span>); </span> </li> <li class="alt"><span>} </span></li> <li> <span>tcon(); </span><span class="comment">//Call the function and write the function name directly. </span><span> </span> </li> <li class="alt"><span></script>

    Second case: Called in an HTML file, such as calling a defined function after clicking a button.

    This situation will be used later.
    The function
    with parameters has the following format:

    JavaScript CodeCopy content to clipboard
    1. function Function name (parameter 1, parameter 2)
    2. {
    3. Function code
    4. }

    Note: There can be multiple parameters, increase or decrease the number of parameters as needed. Parameters are separated by (comma,).
    According to this format, the function to implement the sum of any two numbers should be written as:

    JavaScript CodeCopy content to clipboard
    1. function add2(x,y)
    2. {
    3. sum = x y;
    4. document.write(sum);
    5. }

    x and y are the two parameters of the function. When calling the function, we can pass the two actual addends to the function through these two parameters.
    For example, add2(3,4) will find the sum of 3 4, and add2(60,20) will find the sum of 60 and 20.
    Return value function

    JavaScript CodeCopy content to clipboard
    1. function add2(x,y)
    2. {
    3. sum = x y;
    4. return sum; //Return function value, the value after return is called the return value.
    5. }

    The return here is the same as in other languages, but in weakly typed languages ​​such as JS or AS, the return value type does not need to be written in the function declaration.

    At this point, we have also systematically talked about JavaScript functions. Let’s get back to the topic~
    We can also encapsulate our rectangle, the code is as follows:

    JavaScript CodeCopy content to clipboard
    1.   
    2. "zh">   
    3.   
    4.     "UTF-8">   
    5.     封装绘制矩形方法   
    6.   
    7.   
    8. "canvas-warp">   
    9.     "canvas" style="border: 1px solid #aaaaaa; display: block; margin: 50px auto;">   
    10.         你的浏览器居然不支持Canvas?!赶快换一个吧!!   
    11.        
      
  •   
  • <script>   </span></li> <li class="alt"> <span>    window.onload = </span><span class="keyword">function</span><span>(){   </span> </li> <li> <span>        </span><span class="keyword">var</span><span> canvas = document.getElementById(</span><span class="string">"canvas"</span><span>);   </span> </li> <li class="alt"><span>        canvas.width = 800;   </span></li> <li><span>        canvas.height = 600;   </span></li> <li class="alt"> <span>        </span><span class="keyword">var</span><span> context = canvas.getContext(</span><span class="string">"2d"</span><span>);   </span> </li> <li><span>  </span></li> <li class="alt"> <span>        drawRect(context, 150, 50, 50, 50, </span><span class="string">"red"</span><span>, 5, </span><span class="string">"blue"</span><span>);   </span> </li> <li> <span>        drawRect(context, 250, 50, 50, 50, </span><span class="string">"green"</span><span>, 5, </span><span class="string">"red"</span><span>);   </span> </li> <li class="alt"> <span>        drawRect(context, 350, 50, 50, 50, </span><span class="string">"yellow"</span><span>, 5, </span><span class="string">"black"</span><span>);   </span> </li> <li><span>    }   </span></li> <li class="alt"><span>  </span></li> <li> <span>    </span><span class="keyword">function</span><span> drawRect(cxt, x, y, width, height, fillColor, borderWidth, borderColor){   </span> </li> <li class="alt"><span>        cxt.beginPath();   </span></li> <li><span>        cxt.moveTo(x, y);   </span></li> <li class="alt"><span>        cxt.lineTo(x   width, y);   </span></li> <li><span>        cxt.lineTo(x   width, y   height);   </span></li> <li class="alt"><span>        cxt.lineTo(x, y   height);   </span></li> <li><span>        cxt.lineTo(x, y);   </span></li> <li class="alt"><span>        cxt.closePath();   </span></li> <li><span>  </span></li> <li class="alt"><span>        cxt.lineWidth = borderWidth;   </span></li> <li><span>        cxt.strokeStyle = borderColor;   </span></li> <li class="alt"><span>        cxt.fillStyle = fillColor;   </span></li> <li><span>  </span></li> <li class="alt"><span>        cxt.fill();   </span></li> <li><span>        cxt.stroke();   </span></li> <li class="alt"><span>    }   </span></li> <li><span></script>   
  •   
  •   
  •   
  •   
  • 运行结果:
    2016321105735875.jpg (850×500)

    使用rect()方法绘制矩形
    犹豫绘制矩形是常用的方法,所以在Canvas API中已经帮我们封装好了一个绘制矩形的方法——rect()。这个方法接收4个参数x, y, width, height,实际调用时也就是

    JavaScript Code复制内容到剪贴板
    1. context.rect(x,y,width,height);

    Based on this, let’s optimize the encapsulation method just now.

    JavaScript CodeCopy content to clipboard
    1. function drawRect(cxt, x, y, width, height, fillColor, borderWidth, borderColor){
    2. cxt.beginPath();
    3. cxt.rect(x, y, width, height);
    4. //cxt.closePath(); You don’t need closePath()
    5. cxt.lineWidth = borderWidth;
    6. cxt.strokeStyle = borderColor;
    7. cxt.fillStyle = fillColor;
    8. cxt.fill();
    9. cxt.stroke();
    10. }

    Call the encapsulation method and draw a magical image
    Create a magical image~
    2016321105759647.jpg (500×375)

    Okay, let’s use it to perform surgery, practice our hands, and move the muscles and bones in the way we just packaged it.

    JavaScript CodeCopy content to clipboard
    1.   
    2. "zh">   
    3.   
    4.     "UTF-8">   
    5.     绘制魔性图形   
    6.   
    7.   
    8. "canvas-warp">   
    9.     "canvas" style="border: 1px solid #aaaaaa; display: block; margin: 50px auto;">   
    10.         你的浏览器居然不支持Canvas?!赶快换一个吧!!   
    11.        
      
  •   
  • <script>   </span></li> <li class="alt"> <span>    window.onload = </span><span class="keyword">function</span><span>(){   </span> </li> <li> <span>        </span><span class="keyword">var</span><span> canvas = document.getElementById(</span><span class="string">"canvas"</span><span>);   </span> </li> <li class="alt"><span>        canvas.width = 800;   </span></li> <li><span>        canvas.height = 600;   </span></li> <li class="alt"> <span>        </span><span class="keyword">var</span><span> context = canvas.getContext(</span><span class="string">"2d"</span><span>);   </span> </li> <li><span>  </span></li> <li class="alt"><span>        context.beginPath();   </span></li> <li><span>        context.rect(0, 0, 800, 600);   </span></li> <li class="alt"> <span>        context.fillStyle = </span><span class="string">"#AA9033"</span><span>;   </span> </li> <li><span>  </span></li> <li class="alt"><span>        context.fill();   </span></li> <li><span>  </span></li> <li class="alt"><span>        context.beginPath();   </span></li> <li> <span>        </span><span class="keyword">for</span><span>(</span><span class="keyword">var</span><span> i=0; i<=20; i ){   </span> </li> <li class="alt"><span>            drawWhiteRect(context, 200   10 * i, 100   10 * i, 400 - 20 * i, 400 - 20 * i);   </span></li> <li><span>            drawBlackRect(context, 205   10 * i, 105   10 * i, 390 - 20 * i, 390 - 20 * i);   </span></li> <li class="alt"><span>        }   </span></li> <li><span>  </span></li> <li class="alt"><span>        context.beginPath();   </span></li> <li><span>        context.rect(395, 295, 5, 5);   </span></li> <li class="alt"> <span>        context.fillStyle = </span><span class="string">"black"</span><span>;   </span> </li> <li><span>        context.lineWidth = 5;   </span></li> <li class="alt"><span>  </span></li> <li><span>        context.fill();   </span></li> <li class="alt"><span>        context.stroke();   </span></li> <li><span>    }   </span></li> <li class="alt"><span>  </span></li> <li> <span>    </span><span class="keyword">function</span><span> drawBlackRect(cxt, x, y, width, height){   </span> </li> <li class="alt"><span>        cxt.beginPath();   </span></li> <li><span>        cxt.rect(x, y, width, height);   </span></li> <li class="alt"><span>  </span></li> <li><span>        cxt.lineWidth = 5;   </span></li> <li class="alt"> <span>        cxt.strokeStyle = </span><span class="string">"black"</span><span>;   </span> </li> <li><span>  </span></li> <li class="alt"><span>        cxt.stroke();   </span></li> <li><span>    }</span></li> <li class="alt"><span> </span></li> <li> <span> </span><span class="keyword">function</span><span> drawWhiteRect(cxt, x, y, width, height){ </span> </li> <li class="alt"><span> cxt.beginPath(); </span></li> <li><span> cxt.rect(x, y, width, height); </span></li> <li class="alt"><span> </span></li> <li><span> cxt.lineWidth = 5; </span></li> <li class="alt"> <span> cxt.strokeStyle = </span><span class="string">"white"</span><span>; </span> </li> <li><span> </span></li> <li class="alt"><span> cxt.stroke(); </span></li> <li><span> } </span></li> <li class="alt"><span></script>
  • Run result:
    2016321105841741.jpg (850×500)

    Isn’t it very magical? Isn't it very cool? I won’t take the time to explain this code. You can think about it after class, or you can try to use the knowledge you have learned to draw a cool image. This lesson has a lot of content. In fact, it only introduces four properties and methods - closePath(), fillStyle, fill(), rect(), and an extended JavaScript function explanation.

    Canvas achieves picture rounded corner effect
    This rule applies to regular or irregular graphics drawn by various Canvas.

    The key to achieving rounded corners in Canvas is to use "texture fill".

    There is a method called createPattern in Canvas, which can convert picture elements of known sizes into texture objects for filling.

    For example, if you implement the circular effect of a picture named test.jpg with a size of 100px * 100px, the main JS code is as follows:

    JavaScript CodeCopy content to clipboard
    1. // canvas element, picture element
    2. var canvas = document.querySelector("#canvas"), image = new Image();
    3. var context = canvas.getContext("2d");
    4. image.onload = function() {
    5. // Create image texture
    6.  var pattern = context.createPattern(image, "no-repeat"); 
    7. //Draw a circle
    8. context.arc(50, 50, 50, 0, 2 * Math.PI);
    9. // Fill the drawn circle
    10. context.fillStyle = pattern;
    11. context.fill();
    12. };
    13. image.src = "test.jpg";

    Just make the fillStyle attribute value of the Canvas context equal to this texture object.

    The rectangle drawing API that comes with Canvas does not have rounded corner attributes. Therefore, the rounded rectangle in the demo uses a custom method. I took a quick look and found that it was a little fiddly to achieve different fillet sizes in the vertical and horizontal directions. For the purpose of demonstration, I didn’t go to great lengths, so the fillets in the demo were symmetrical.
    2016321105911393.png (319×314)

    Related labels:
    source:php.cn
    Previous article:HTML5 implements multiple image upload function_html5 tutorial skills Next article:HTML5 css3 progress bar countdown animation special effects code [recommended]_html5 tutorial skills
    Statement of this Website
    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
    Latest Articles by Author
    Latest Issues
    Related Topics
    More>
    Popular Recommendations
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template