1. 创建canvas画布
- 通过标签创建
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
您的浏览器不支持 HTML5 canvas 标签。
</canvas>
2.绘制矩形
<script>
//首先拿到canvas对象
var mycanvas=document.getElementById("myCanvas");
//根据canvas对象创建context
var context=mycanvas.getContext("2d");
//设置绘画样式
context.fillStyle="#FF0000";
//旋转
//context.rotate(45);
//平移x轴20px,y轴20px
//context.translate(20,20);
//放大缩小,x轴放大2倍,y轴0.5倍
context.scale(2,0.5);
//画矩形,起点0,0,x轴150px,y轴75px
context.fillRect(0,0,150,75);
</script>
3.绘制圆
arc(x,y,r,start,stop)
<script>
//首先拿到canvas对象
var mycanvas=document.getElementById("myCanvas");
//根据canvas对象创建context
var context=mycanvas.getContext("2d");
//设置绘画样式
context.beginPath();
//参数圆心x、y轴坐标,半径,0,角度
context.arc(20,20,20,0,Math.PI);
context.fillStyle="#FF0000";
context.closePath();
context.fill();
</script>
<script>
//首先拿到canvas对象
var mycanvas=document.getElementById("myCanvas");
//根据canvas对象创建context
var context=mycanvas.getContext("2d");
//设置绘画样式
for(let i=0;i<10;i++){
context.beginPath();
//参数圆心x、y轴坐标,半径,0,角度
context.arc(i*20,i*20,i*10,0,Math.PI*2);
context.fillStyle="rgba(255,0,0,0.25)";
context.closePath();
context.fill();
}
</script>
4.绘制路径
moveTo(x,y) 定义线条开始坐标
lineTo(x,y) 定义线条结束坐标
<script>
//首先拿到canvas对象
var mycanvas=document.getElementById("myCanvas");
//根据canvas对象创建context
var context=mycanvas.getContext("2d");
//设置绘画样式
context.moveTo(0,0);
context.lineTo(200,100);
context.stroke();
</script>
5.绘制渐变
createLinearGradient(x,y,x1,y1) - 创建线条渐变
createRadialGradient(x,y,r,x1,y1,r1) - 创建一个径向/圆渐变
图片.png
网友评论