canvas的基本用法

<canvas>

作用:在页面中设定一个区域,然后通过JavaScript动态在这个区域中绘制图片

基本用法:

1、要使用canvas元素标签,一定要设置width和height

2、也可以通过CSS对他的样式进行修改

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>canvas基本用法</title>
  <style type="text/css">
    #drawing{
      background-color: red;
    }
  </style>
</head>
<body>
  <canvas id="drawing" width="450" height="450">A drawing og something</canvas>
</body>
</html>

3、getContext()方法一定要在canvas的后面出现,不能在canvas前面出现

<!DOCTYPE html>
<html>
  <head>
  <meta charset="utf-8" />
  <title>canvas基本用法</title>
  <style type="text/css">
    #drawing{
      background-color: red;
    }
  </style>

  </head>
  <body>
  <canvas id="drawing" width="450" height="450">A drawing og something</canvas>
  <script type="text/javascript">
    var drawing = document.getElementById("drawing")
    if(drawing.getContext){
      var context = drawing.getContext("2d")
      console.log(context)
    }
  </script>
  </body>
</html>

4、toDataURL()方法,

其中他的参数:图片格式,例如:image/png(默认是这个格式)

返回值为:图片的信息(在画布上面画的图片):包括:data:图片格式;base64,图片信息

语法为:HTMLCanvasElement.toDataURL()

<!DOCTYPE html>
<html>
  <head>
  <meta charset="utf-8" />
  <title>canvas基本用法</title>
  <style type="text/css">
    #drawing{
      background-image: url(img/20181029230459.jpg);
      /*background-color: red;*/
    }
  </style>

  </head>
  <body>
  <img id="forget" />
  <canvas id="drawing" width="550" height="550">A drawing og something</canvas>

  <script type="text/javascript">
    var drawing = document.getElementById("drawing")
    if(drawing.getContext){
      var imgURL = drawing.toDataURL("image/jpeg")
      console.log(imgURL)

      var imgb = document.createElement("img")
      var image = document.getElementById("forget")
      image.src = imgURL
    }
  </script>
  </body>
</html>

之前出现了一个bug:

Uncaught TypeError: Cannot set property ' ' of null

这是因为之前给的id不存在,或者可以说是不给id

之前的错误代码:var image = document.getElementById("img")

posted @ 2018-11-18 01:06  Myuniverse  阅读(517)  评论(0编辑  收藏  举报