5.Canvas【画布】

5.Canvas画布

1.设置绘画区域
<style>
  #myCanvas {
    border: 1px solid black
  }
</style>
<body>
  <canvas id="myCanvas" width="200" height="200"></canvas>
</body>
<script>
  window.onload = function () {
    let canvas = document.getElementById("myCanvas");
    let ctx = canvas.getContext("2d");
  }
</script>
2.线条
ctx.beginPath(); //开始路径
ctx.strokeStyle = 'black';  //边框颜色,默认黑
ctx.lineWidth = 10;      //边框宽度,内外各一半扩大 

ctx.stroke()    //线条
ctx.closePath(); //结束路径
3.填充
ctx.beginPath(); //开始路径
ctx.fillStyle = 'black';//填充的颜色,默认黑

ctx.fill()      //填充
ctx.closePath(); //结束路径
4.矩形
ctx.fillRect(x,y,width,height); //填充矩形  
ctx.strokeRect(x,y,width,height); //画矩形框
ctx.clearRect(x,y,width,height); //清除矩形,擦除橡皮工具
5.圆弧
//圆心x位置,圆心y位置,半径,起始位置,结束位置,顺逆时针
ctx.arc(x, y, 100, Math.PI*3/2,0, flase);

flase   //顺时针
true    //逆时针
0 = 0°          //右侧
Math.PI/2 = 90° //下侧
Math.PI = 180°  //左侧
Math.PI*3/2 = 270°  //上侧
Math.PI*2 = 360°
6.线段
ctx.moveTo(x,y);  //起始位置
ctx.lineTo(x,y);  //目标位置
7.文本
ctx.font="30px Arial";                //定义字体
ctx.strokeStyle="#ccc";               //字体颜色
ctx.strokeText("Hello World",12,52);  //空心文本
ctx.fillText("Hello World",10,50);    //实心文本
8.插入图片
<canvas id="mycanvas" width="500" height="500" ></canvas>
<img src="./eg_tulip.jpg" alt="图片" style="display:none;" id="img1">

<script>
        var canvas = document.getElementById('mycanvas'); //获得元素
        var ctx = canvas.getctx('2d');
        var img = document.getElementById("img1");//获取图片
        img.onload = function(){    //加载需要时间,用onload
            ctx.drawImage(img,10,10);
        }           
</script>
9.旋转和缩放
ctx.rotate(Math.PI/4);  //顺时针旋转45度
ctx.scale(50%, 50%);    //缩放
10.环形圆
<style>
  #myCanvas {
    border: 1px solid black
  }
</style>
<body>
  <canvas id="myCanvas" width="200" height="200"></canvas>
</body>
<script>
  window.onload = function () {
    let canvas = document.getElementById("myCanvas");
    let ctx = canvas.getContext("2d");
    ctx.strokeStyle = 'yellow'
    ctx.lineWidth = 10
    ctx.arc(100, 100, 80, 0, Math.PI*2, false)
    ctx.stroke()
  }
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。