Home > Web Front-end > HTML Tutorial > canvas basics

canvas basics

高洛峰
Release: 2016-11-03 16:58:41
Original
1152 people have browsed it

1.元素

<canvas id="tutorial" width="150" height="150"></canvas>
Copy after login

替换内容

元素不同于在其中的canvas basics标签,就像

<canvas id="stockGraph" width="150"    style="max-width:90%">
  current stock price: $3.15 +0.15
</canvas>

<canvas id="clock" width="150" height="150">
  <img src="images/clock.png" width="150"    style="max-width:90%" alt=""/>
</canvas>
Copy after login

标签不可省

2.渲染上下文(The rendering context)

WebGL 使用了基于OpenGL ES的3D上下文 ("experimental-webgl")

我们将会将注意力放在2D渲染上下文中

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

var canvas = document.getElementById(&#39;tutorial&#39;);
var ctx = canvas.getContext(&#39;2d&#39;);
Copy after login

3.检查支持性

var canvas = document.getElementById(&#39;tutorial&#39;);

if (canvas.getContext){
  var ctx = canvas.getContext(&#39;2d&#39;);
  // drawing code here
} else {
  // canvas-unsupported code here
}
Copy after login

4.一个模板骨架


  
    Canvas tutorial
    
    
  
<canvas id="tutorial" width="150" height="150"></canvas>
Copy after login

5.一个简单例子

<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>
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template