canvas的常见的知识


canvas只有两个基本的属性,width和heigtht两个属性

<canvas id="tutorial" width="150" height="150"></canvas>
canvas起初是空白的。为了展示,首先脚本需要找到渲染上下文,然后在它的上面绘制。<canvas> 元素有一个叫做 getContext() 的方法,这个方法是用来获得渲染上下文和它的绘画功能。getContext()只有一个参数,上下文的格式。对于2D图像而言,可以使用 CanvasRenderingContext2D


例子:

<html>
  <head>
    <title>Canvas tutorial</title>
    <script type="text/javascript">
      function draw(){
        var canvas = document.getElementById('tutorial');
        if (canvas.getContext){
          var ctx = canvas.getContext('2d');
        }
      }
    </script>
    <style type="text/css">
      canvas { border: 1px solid black; }
    </style>
  </head>
  <body onload="draw();">
    <canvas id="tutorial" width="150" height="150"></canvas>
  </body>
</html>


列子:

扫描二维码关注公众号,回复: 2620567 查看本文章
<html>
 <head>
  <script type="application/javascript">
    function draw() {
      var canvas = document.getElementById("canvas");
      if (canvas.getContext) {
        var ctx = canvas.getContext("2d");

        ctx.fillStyle = "rgb(200,0,0)";
        ctx.fillRect (10, 10, 55, 50);

        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
        ctx.fillRect (30, 30, 55, 50);
      }
    }
  </script>
 </head>
 <body onload="draw();">
   <canvas id="canvas" width="150" height="150"></canvas>
 </body>
</html>

所有API调用都是基于自定义的对象 var context = document.getElementById("myCanvas").getContext("2d");

列子:

将画布内容导出为图像

   document.getElementById("myCanvas").toDataURL()

属性

lineWidth 影响stroke方法绘制出轮廓的宽度,例:

context.lineWidth =4;

strokeStyle 影响stroke方法绘制出轮廓的颜色,例:

context.strokeStyle="#00FF00";

context.strokeStyle="red";

 illStyle 影响fill方法绘制出图形的填充色,例:

 context.fillStyle="#00FF00";

 context.fillStyle="red";


参考资料:

W3C标准:http://www.w3.org/TR/2012/WD-2dcontext-20120329/

中文介绍(部分):http://www.w3school.com.cn/htmldom/dom_obj_canvasrenderingcontext2d.asp 

canvas官方文档: https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Tutorial/Basic_usage

猜你喜欢

转载自blog.csdn.net/weixin_39654784/article/details/78791597