Skip to content

01-Canvas概述

认识canvas

canvas是一个行内块元素

html
<canvas id="canvas"></canvas>

绘制canvas有三个步骤:

  1. 获取canvas对象
  2. 获取上下文环境对象context
  3. 开始绘制图形
js
window.onload = function() {
    // 1. 获取canvas对象
    const cnv = document.getElementById('canvas');
    // 2. 获取上下文环境对象context
    const cxt = cnv.getContext('2d');
    // 3. 开始绘制图形
    cxt.moveTo(50, 100);
    cxt.lineTo(150, 50);
    cxt.stroke();
}

canvas宽高定义

canvas有三个属性:id、width、height

  • width:canvas元素的宽度,默认是300px
  • height:canvas元素的高度,默认是150px

特别注意

canvas的宽度和高度可以在html中定义,也可以在css中定义,但是css中定义的并不是画布原本的宽高

当前这个画布定义了css宽为200px,高为100px

html
<style>
    #canvas {
        width: 200px;
        height: 100px;
    }
</style>

<canvas id="canvas"></canvas>

认识canvas对象的属性方法

canvas元素的属性

  • width: cnv.width
  • height: cnv.height

canvas元素的方法

  • getContext("2d"): 获取canvas2D上下文环境对象 cnv.getContext("2d")
  • toDataURL: 获取canvas对象产生的位图的字符串 cnv.toDataURL()
    • data:image/png;base64,iVBORw0KGgoAAAANSUhEU...

canvas坐标系

  • 数学坐标系:x正方向向右,y正方向向上
  • W3C坐标系(canvas坐标系):x正方向向右,y正方向向下

兼容

如果要兼容IE7\IE8explorercanvas 这个扩展来解决,下载地址:https://github.com/arv/explorercanvas

只需要向下面一样引用即可,但是依旧会有一些方法不能用,例如:fillText()

html
<!--[if IE]>
    <script src="excanvas.js"></script>
<![end if]-->

MIT Licensed