Cavas和SVG

193 阅读1分钟

1.Cavas的用法

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.fillStyle = 'green';//填充色
ctx.fillRect(10, 10, 150, 100);//画矩形(起始横坐标、起始纵坐标、宽度、高度)
ctx.lineCap='round'//可以让线与线的转折处是圆的

//画圆形
ctx.fillStyle='black'
ctx.strokeStyle='none'
ctx.beginPath();
ctx.arc(75, 75, 50, 0, 2 * Math.PI);//(圆心横坐标、圆心纵坐标、半径、弧度)
ctx.stroke();//描边
ctx.fill();//填充色

//画线
ctx.beginPath();
  ctx.moveTo(0, 0);//线段起始位置
  ctx.lineTo(125, 45);//线段到达位置
  ctx.stroke();
  
//可以让canvas的宽高等于屏幕宽高
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;

//检测是否支持触屏
let isTouchDevice = "ontouchstart" in document.documentElement;

2.SVG的用法

<body>
    <svg>
        <use xlink:href="#icon-shouye"></use>
    </svg>
</body>
<script src="imgs/iconfont.js"></script>
</html>

3.SVG和Canvas的区别

  1. Canvas是用笔刷来绘制2D图形的
  2. SVG是用标签来绘制不规则矢量图的
  3. 相同点:都是用来绘制2D图形的
  4. 不同点:Canvas画的是位图,SVG画的是矢量图
  5. 不同点:SVG支持分层和事件,Canvas不支持
  6. 不同点:SVG节点过多时渲染慢,Canvas性能好一点,但写起来更复杂