canvas的常见的知识

来源:互联网 发布:可视化编程工具 编辑:程序博客网 时间:2024/09/21 08:14


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>


列子:

<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

原创粉丝点击