Home  >  Article  >  Web Front-end  >  利用HTML5 Canvas API绘制矩形的超级攻略_html5教程技巧

利用HTML5 Canvas API绘制矩形的超级攻略_html5教程技巧

WBOY
WBOYOriginal
2016-05-16 15:45:351790browse

使用closePath()闭合图形
首先我们用最普通的方法绘制一个矩形。

JavaScript Code复制内容到剪贴板
  1. nbsp;html>   
  2. "en">   
  3.   
  4.      "UTF-8">   
  5.        
  6.   
  7.   
  8. nbsp;html>   
  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.        
  
  •   
  •     window.onload = function(){   
  •         var canvas = document.getElementById("canvas");   
  •         canvas.width = 800;   
  •         canvas.height = 600;   
  •         var context = canvas.getContext("2d");   
  •   
  •         context.beginPath();   
  •         context.moveTo(150,50);   
  •         context.lineTo(650,50);   
  •         context.lineTo(650,550);   
  •         context.lineTo(150,550);   
  •         context.lineTo(150,50);     //绘制最后一笔使图像闭合   
  •         context.lineWidth = 5;   
  •         context.strokeStyle = "black";   
  •         context.stroke();   
  •   
  •     }   
  •   
  •   
  •   
  •   
  •   
  • 运行结果:
    2016321105129852.jpg (850×500)

    乍一看没啥问题,但是视力好的童鞋已经发现了,最后一笔闭合的时候有问题,导致左上角有一个缺口。这种情况是设置了lineWidth导致的。如果默认1笔触的话,是没有问题的。但是笔触越大,线条越宽,这种缺口就越明显。那么这种情况该怎么避免呢?
    标题已经剧透了,使用clothPath()闭合图形。

    JavaScript Code复制内容到剪贴板
    1. nbsp;html>   
    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.        
      
  •   
  •     window.onload = function(){   
  •         var canvas = document.getElementById("canvas");   
  •         canvas.width = 800;   
  •         canvas.height = 600;   
  •         var context = canvas.getContext("2d");   
  •   
  •         context.beginPath();   
  •         context.moveTo(150,50);   
  •         context.lineTo(650,50);   
  •         context.lineTo(650,550);   
  •         context.lineTo(150,550);   
  •         context.lineTo(150,50);     //最后一笔可以不画   
  •         context.closePath();        //使用closePath()闭合图形   
  •   
  •         context.lineWidth = 5;   
  •         context.strokeStyle = "black";   
  •         context.stroke();   
  •   
  •     }   
  •   
  •   
  •   
  • 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
    Previous article:HTML5实现多张图片上传功能_html5教程技巧Next article:html5+css3进度条倒计时动画特效代码【推荐】_html5教程技巧

    Related articles

    See more