canvas 绘制矩形和圆形

canvas绘制有两神方法:
1)、填充(fill)
填充是将图形内部填满.

2)、绘制边框 (stroke)
绘制边框是不把图形内部填满,只是绘制图形的外框.

当我们在绘制图形的时候,首先要设定好绘制的样式,然后我们就可以调用有关的方法进行绘制

fillStyle属性
填充的样式,在这个属性里面设置填入的填充颜色值

strokeStyle属性
图形边框的样式,在这个属性里面设置填入边框的填充颜色

绘制矩形案例:

在body的属性里面,使用onload="draw('canvas' )“语句,调用脚本文件中的draw函数进行图形绘画

画布的创建方法:指定 id , width(画布宽度), height(画布高度)

创建一个画布,长度为600,高度为400

<body onload="draw('canvas')">
<canvas id="canvas" width="600" height="400"></canvas>
</body>

 

引入一个名为canvas的is脚本,js脚本的语言编码是utf-8

 1 function draw(id){
 2     var canvas = document.getElementById(id);
 3     var context = canvas.getContext('2d');  //getContext() 方法可返回一个对象
 4     context.fillStyle = "green";  // 设置或返回用于填充绘画的颜色、渐变或模式
 5     context.strokeStyle = "#fff";  //图形边框的填充颜色
 6     context.lineWidth = 5;  //用宽度为 5 像素的线条来绘制矩形:
 7     context.fillRect(0,0,400,300);  // x轴 y轴 宽 和 高 ,绘制“被填充”的矩形
 8     context.strokeRect(50,50,180,120);  //绘制矩形(无填充)
 9     context.strokeRect(110,110,180,120);
10 }

使用filiRect方法和strokeRect方法来填充矩形和绘制矩形的边框
context. fillRect (x,y,width,height)
context.strokeRect (x,y,width,height)

这两种方法的参数都是一样的,x是指拒形的起点横坐标,y是指拒形的纵坐标.坐标的原点是canvas画布的最左上角,

width是指拒形的长度,height是指矩形的高度.


绘制圆形案例:

创建圆形路径时,需要使用图形上下文对像的arc方法。

context.arc (x,y,radius,starAngle,endAngle,anticlockwise)

x是绘制圆形的起点横坐标,y是绘创圆形起点的纵坐标,radius是图形的半径,
starAngle是开始的角度,endAngle是结束的角度·

anticlockwise是否按顺时针方向绘制

绘制半径与圆弧时指定参数为开始弧度与结束弧度,也可以把角度换成弧度

var radius = degrees *Math.Pl/180

这个里面的Math.Pl表示的角度是180度,Math.Pl*2的角度是360度.

 1 function draw(id){
 2             var canvas = document.getElementById(id);
 3             var context = canvas.getContext('2d');
 4             context.fillStyle = "#f1f2f3";
 5             context.fillRect(0,0,400,400);
 6             for(var i=0;i<10;i++){
 7 
 8                 context.arc(i*25,i*25,i*10,0,Math.PI*2,true);
 9 
10                 context.fillStyle = "rgba(255,0,0,0.25)";
11                 context.fill();
12 
13     }
14 }

保存文件 

1 function draw(id){
2     var canvas = document.getElementById(id);
3     var context = canvas.getContext('2d');
4     context.fillStyle = "green";
5     context.fillRect(0,0,400,300);
6     window.location = canvas.toDataURL('image/png');
7 }
原文地址:https://www.cnblogs.com/amy-1205/p/6183430.html