html5-canvas

  • 用于图形的绘制,通过脚本 (通常是JavaScript)来完成。
  • <canvas> 创建一个画布  默认情况下 <canvas> 元素没有边框和内容
  • 创建 context 对象 
    •   var c=document.getElementById("myCanvas");
    • var ctx=c.getContext("2d");
  • fillRect 方法矩形   
    • ctx.fillStyle="#FF0000";
    • ctx.fillRect(0,0,150,75);
  • fillStyle  填充颜色 ;strokeStyle 描边
  • beginPath()  开始一个路径函数
  • 路径(线条)
    • moveTo(x,y) 定义线条开始
    • lineTo(x,y) 定义线条结束坐标
    • 使用 stroke() 方法来绘制线条
  • 圆    ctx.arc(x,y,r,圆的起始位置(弧度),圆的结束位置,方向);  true:代表逆时针方向  ,默认是false顺时针方向
  • 文本  
    • font - 定义字体
    • fillText(text,x,y) 实心的文本
    • strokeText(text,x,y)  空心的文本
  • 颜色渐变
    • createLinearGradient(x,y,x1,y1) - 创建线条渐变(x开始坐x1结束点坐标)
    • createRadialGradient(x,y,r,x1,y1,r1) - 创建一个径向/圆渐变  (r1结束圆半径)
    • addColorStop() 方法指定颜色
    • 然后设置fillStyle或strokeStyle的值为渐变
    • 填充
 
 1 <body>
 2     <canvas id="myCanvas" width="400" height="400" style="border:1px solid red"></canvas>
 3 </body>
 4 <script>
 5     var c = document.getElementById('myCanvas');
 6     var ctx = c.getContext("2d");
 7     // 红色矩形
 8     ctx.beginPath()
 9     ctx.fillstyle = "#FF0000";
10     ctx.fillRect(0, 0, 150, 75);
11     // 路径
12     ctx.beginPath()
13     ctx.moveTo(0, 0);
14     ctx.lineTo(200, 100);
15     ctx.strokeStyle = "red";
16     ctx.stroke();
17     // 三角形
18     ctx.beginPath()
19     ctx.moveTo(10, 10);
20     ctx.lineTo(50, 50);
21     ctx.lineTo(10, 50);
22     ctx.lineTo(10, 10);
23     ctx.stroke();
24     // 创建渐变
25     var grd = ctx.createLinearGradient(100, 150, 200, 30);
26     grd.addColorStop(0, "red");
27     grd.addColorStop(1, "blue");
28     //
29     ctx.beginPath();
30     ctx.font = "30px Arial";
31     ctx.fillStyle = grd;
32     ctx.fillText("Hello World", 100, 150);
33     ctx.fill();
34     //
35     ctx.beginPath();
36     ctx.fillStyle = 'black';
37     ctx.arc(250, 250, 50, 0, 2 * Math.PI, true);
38     ctx.fill();
39 </script>
原文地址:https://www.cnblogs.com/hjcby/p/13527217.html