<canvas>画布标签</canvas>,默认情况下是300px*150px的矩形画布,可自定义大小或添加其他属性。
利用Canvas实现绘画,并不是通过鼠标绘画的,而是用户需要通过JavaScript来控制画布中的内容,例如添加图片、线条、文字等。
画布绘制三角形js步骤:
<body>
<canvas id="canvas">您的浏览器版本不支持画布,请更新浏览器</canvas>
<script type="text/javascript">
//1. 获取一个画布(要创建一个画布对象)
var canvas=document.getElementById("canvas");
//2. 创建一个画布上下文对象
var context=canvas.getContext("2d");
//3. 告诉程序绘画路径开始
context.beginPath();
//4. 绘制图形的起始点(坐标)
context.moveTo(10,10);
//5. 绘制图形的连接点
context.lineTo(10,100);
context.lineTo(100,100);
context.closePath();
//6. 设置图形的样式
context.lineWidth=10;//设置线的粗细
context.strokeStyle="red";//设置图形颜色
//7. 描边
context.stroke();
context.fillStyle = "green";//填充图形颜色
context.fill();//填充
</script>
</body>
画布for循环做虚线:
//1.获取一个画布(要创建一个画布对象)
var canvas = document.getElementById("canvas");
//2.创建一个画布上下文的对象
var context = canvas.getContext("2d");
for (var i = 0; i < 30; i++) {
//3.告诉程序绘画路径开始
context.beginPath();
//4.绘制图形的起始点(坐标)
context.moveTo(10 * i, 0);
//5.绘制图形的连接点
context.lineTo(10 * i + 5, 0);
context.closePath();//封闭路径
//6.设置图形的样式
context.strokeStyle = "red";
//7.描边
context.stroke();
}
虚线效果图:
绘制无填充矩形:
context.strokeStyle="red";
context.strokeRect(0,0,200,100);//(x轴,y轴,宽,高)
绘制填充矩形:
context.fillStyle="red";
context.fillRect(0,0,200,100);//(x轴,y轴,宽,高)
// 橡皮擦(x轴,y轴,宽,高)
context.clearRect(10,10,20,20);
绘制圆形:
//context.arc(x,y,r,start,stop,[counterlockwise])
//参数(圆心x,圆心y,半径r,起始角,结束角,顺时针(true)/逆时针(false))
c.beginPath();
c.arc(150, 150, 10, 0, Math.PI * 2, true);
c.stroke();
c.fillStyle = "blue"; //填充图形颜色
c.fill(); //填充
绘制椭圆:
context.ellipse(x,y,radiusX,radiusY,rotation,startAngle,endAngle,anticlockwise)
//参数:
//(椭圆圆心x,椭圆圆心y,半径r,半径y,旋转的角度,起始角,结束角,顺时针(true)/逆时针(false))