canvas画布

简介:
属于html元素 H5新元素 需要结合js 用来绘制图形
在页面上放置一个canvas元素 就相当于放置了一块画布
可以绘制路径 矩形 圆形 字符 图像…
属性:
width 默认值 300px
height 默认值 150px
注意点:canvas需要写闭合标签

一般不建议使用css设置它的宽高
方法:

 <canvas id="canvas" width="300" height="300"></canvas>

 <sctript>
    // var canvas=document.getElementById('canvas');
    var canvas=$('#canvas')[0];
    //检查浏览器是否支持canvas
    if(canvas.getContext){
        //支持canvas
        var ctx=canvas.getContext('2d');
        ctx.beginPath();
    }else{
        console.log("您的浏览器不支持canvas")
    }
</script>
</script>

1.绘制一个矩形图案(填充)
fillRect(x,y,width,height)
2.绘制矩形边框
strokeRect(x,y,width,height)
3.清除指定矩形区域,让清除部分完全透明
clearRect(x,y,width,height)
步骤:
1.获取画布
2.获取上下文对象context–获取画笔
var context=canvas.getContext(‘2d’);
3.绘制填充样式
4.绘制图形
绘制步骤:

  1. 新建一条路径
    然后通常会使用moveTo去设置你的起始位置
  2. 然后去绘制路径
    beginPath()
  3. 闭合路径
    如果我们绘制的路径自己就是闭合的 那我们不需要调用这个方法
    closePath()

4.一旦路径生成,就能通过描边或填充路径区域来渲染图形
方法:

  1. fill()
    填充路径的内容区域 可以不用 closePath()
    2.stroke()
    通过线条绘制图形轮廓 需要使用 closePath()
    3.moveTo(x, y)
    通过线条绘制图形轮廓,需要使用closePath()
    4.lineTo(x, y)
    绘制一条从当前位置到指定x以及y位置的直线
    5.绘制圆弧
    arc(x,y,r,startAngle,endAngle,anticlockwise)
    anticlockwise:默认顺时针方向
  ctx.arc(100, 100, 60, 0, 2 * Math.PI);

6.fillStyle()
控制色彩
颜色值 red #000999 rgb rgba
7.strokeStyle()
描述颜色或者样式的属性。默认值是 #000 (black)。
8.lineWidth()
设置线段厚度的属性(即线段的宽度)。
9.addColorStop(offset, color)
设置渐变色
offset
0到1之间的值

实例
1.五角星

  <div id="app">
        <canvas id="canvas" width="500px" height="500px"></canvas>
    </div>
<script>
    var canvas=document.getElementById('canvas');
    var ctx=canvas.getContext('2d');
    ctx.beginPath();
    ctx.moveTo(170,40);
	ctx.lineTo(210,130);
	ctx.lineTo(320,150);
	ctx.lineTo(230,200);
	ctx.lineTo(260,300);
    ctx.lineTo(170,230);
    ctx.lineTo(90,300);
    ctx.lineTo(110,200);
    ctx.lineTo(30,150);
    ctx.lineTo(130,130);
    ctx.fillStyle = 'red';
    // ctx.strokeStyle='yellow';
    // ctx.closePath();
    ctx.fill();
</script>

2.奥运五环

<script>
    var canvas=$("canvas")[0];
    var ctx=canvas.getContext('2d');
        ctx.lineWidth=5;
        ctx.beginPath();
        ctx.strokeStyle='blue';
        ctx.arc(80,80,60,0,Math.PI * 2);
        ctx.stroke();
        
        ctx.beginPath();
        ctx.strokeStyle='black';
        ctx.arc(210,80,60,0,Math.PI * 2);
        ctx.stroke();
        
        ctx.beginPath();
        ctx.strokeStyle='red';
        ctx.arc(340,80,60,0,Math.PI * 2);
        ctx.stroke();

        ctx.beginPath();
        ctx.strokeStyle='yellow';
        ctx.arc(145,140,60,0,Math.PI * 2);
        ctx.stroke();

        ctx.beginPath();
        ctx.strokeStyle='green';
        ctx.arc(275,140,60,0,Math.PI * 2);
        ctx.stroke();

</script>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值