Canvas 画布学习(补全中...)

发布时间 2023-08-06 20:41:29作者: 贲风

1. 标签 <canvas></canvas>

2.大小

  可以在标签中直接写

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

  也可以在Css中为id类添加样式

  

#canvas {
    background-color: red;
    width:520px;
    height:200px;
}

也可以在JS中赋值

var canvas = document.querySelector('#canvas')
canvas.width = window.innerWidth
canvas.height = 300

默认大小 300 150  不推荐多种方式一起使用

3.线

  var ctx = canvas.getContext('2d');

  // 开始画线

  ctx.beginPath()

  // 移动到起点

  ctx.moveTo(x,y)  x,y 为坐标点

  // 画线连接两个点

  ctx.lineTo(x,y)fi

  ¥¥  // 这里也可以用 ctx.closePath()  闭合线段 或 ctx. fill() 填充闭合线段

  // 绘制出定义的线

  ctx.stroke()

4.矩形

  //画一个矩形 起点坐标 x,y 宽 高

  ctx.rect(0,0, 400,200) 

  // 接着可以 闭合填充矩形 也可以只是绘制出闭合的矩形  ctx.fill()  ctx.stroke()

  // 也可以将上面绘制和闭合 一起使用

  ctx.fillRect(0,0,400,200)   or  ctx.strokeRect(0,0,400,200)

  // 清除指定区域内的任何画笔痕迹

  ctx.clearRect(0,0,200,200)

5.圆形

  // 画一个矩形 x,y 圆心 r 半径 startAngle 开始角度 endAngle 结束角度 anticlockwise true 逆时针 false 顺时针 默认false

  ctx.arc(x,y,r,startAngle,endAngle,anticlockwise)

6.文字

  // 绘制文字  text 文字内容 x,y 坐标

  ctx.fillText(text,x,y)

  // 绘制文字 text 文字内容  x,y 坐标  和上面的区别 我用起来的感觉就是这个是加粗 具体的后面在看吧

  ctx.strokeText(text,x,y)

  // 字体 和CSS一样

  ctx.font()

  // 文本居中方式  left | right | center | start | end 

  ctx.textAlign()

  // 基线对齐方式 top | hanging | middle | alphabetic | ideographic

  ctx.textBaseline()

  // 文字方向 ltr | rtl | inherit

  ctx.direction 

7.图片

  var img = new Image()

  //  图片地址

  img.src = ''

  // 绘制图片  img 图片对象 x,y 坐标 width 宽 height 高

  ctx.drawImage(img,x,y,width,height)

  $$ 这里我遇到了这样写图片不显示的问题 应该是显示时机的问题 改为如下写法即可显示

  var myImage= new Image()

  myImage.onLoad = ()=>{

    ctx.drawIamge(myImage,x,y,width,height)

  }

  //  写图片地址 

  myImage.src = ''

8.样式

  //填充颜色  我怎么没用处效果呢...

   ctx.fillStyle('blue')

  //填充颜色  我怎么没用处效果呢...

  ctx.strokeStyle('blue')

9.状态

  // 存储当前的值 颜色等

  ctx.save()

  // 恢复到存储的值

  ctx.restore()

10.