Canvas基础

192 阅读2分钟

Canvas 画图

起步

  1. 创建 Canvas 画布

    <canvas></canvas>
    
  2. 绘图

    1. 获取上下文
    var drawing = document.getElementById("drawing");
    //确定浏览器支持<canvas>元素
    if (drawing.getContext) {
      var context = drawing.getContext("2d");
      //更多代码
    }
    
    1. 2D 上下文

      1. 开始绘图 beginPath()
      2. 移动笔触 moveTO(x, y) 移动到你想要的起始点
      3. 闭合路径 closePath()
        • 不是必需的。这个方法会通过绘制一条从当前点到开始点的直线来闭合图形。如果图形是已经闭合了的,即当前点为开始点,该函数什么也不做。
      4. 通过线条来绘制路径 stroke()
      5. 通过填充来绘制路径 fill()
    2. save()和 restore()

填充和描边

  • fillStyle
  • strokeStyle
  • lineWidth
context.strokeStyle = "red";
context.fillStyle = "#0000ff";
// 设置线宽
context.lineWidth = 3;

绘制直线

  1. lineTo(x, y)

绘制矩形

  1. 创建矩形 rect(x, y, width, height)

    • 当该方法执行的时候,moveTo()方法自动设置坐标参数(0,0)。也就是说,当前笔触自动重置回默认坐标。
  2. 绘制被填充的矩形 fillRect() 需要填充函数一起使用

//绘制红色矩形
context.fillStyle = "#ff0000";
context.fillRect(10, 10, 50, 50);
  1. 绘制无填充的矩形 stroleRect() 需要和描边函数一起用
  2. 在给定的矩形内消除元素 clearRect()
    • 本质上,这个方法可以把绘制上下文中的某一矩形区域变透明。通过绘制形状然后再清除指定区域,就可以生成有意思的效果。

绘制圆弧

  1. arc(x, y, radius, startAngle, endAngle, anticlockwise)
    1. anticlockwise 默认顺时针 false
    2. startAngle 表示弧度,弧度=(Math.PI/180)*角度
  2. 绘制圆/圆弧不需要移动笔触 moveTo(x, y),直接绘制就可以
  3. arcTo(x1, y1, x2, y2, radius)

绘制文本

  1. fillText(text, x, y [, maxWidth])
  2. strokeText(text, x, y [, maxWidth])
  3. 有很多方式可以改变显示文本的属性,比如 font、textAlign、direction 等

变换

  1. scale(x, y) 缩放
  2. rotate(angle) 旋转
  3. translate(x, y) 移动
  4. transform(a, b, c, d, e, f) 变形
  5. setTransform()

绘制图像

  1. drawImage(image, x, y)
    • image 是 canvas 或 img 对象
    • x, y 是起始坐标
  2. 缩放 drawImage(image, x, y, width, height)
  3. 剪切 drawImage(img,sx,sy,swidth,sheight,x,y,width,height)

阴影

context.shadowOffsetX = 15;
context.shadowOffsetY = 15;
context.shadowBlur = 5;
context.shadowColor = "rgba(0, 0, 0, 0.5)";

渐变

  1. createLinearGradient()
  2. createRadialGradient()
  3. addColorStop()