>  기사  >  웹 프론트엔드  >  JavaScript는 Canvas를 사용하여 그리기 그래픽을 구현합니다.

JavaScript는 Canvas를 사용하여 그리기 그래픽을 구현합니다.

不言
不言원래의
2018-06-25 14:36:172961검색

이 글은 Canvas를 사용하여 그래픽을 그리는 데 JavaScript를 사용하는 기본 튜토리얼을 주로 소개합니다. 이는 특정 참조 가치가 있으며 관심 있는 친구들이 참조할 수 있습니다.

최근 2년간 HTML5가 큰 인기를 끌면서 연구를 좀 했는데요, 최근 HTML 관련 기능을 활용해볼까 하는 생각이 들어서 저도 잘 배워야 겠습니다.

Canvas의 기능을 잘 살펴보았습니다. HTML5가 클라이언트 측 상호작용에서 점점 더 기능적으로 변하고 있다는 것을 느꼈습니다. 오늘은 나중에 사용할 수 있도록 몇 가지 예를 살펴보았습니다. .

1. Canvas를 사용하여 직선 그리기:

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <style type="text/css">
    canvas{border:dashed 2px #CCC}
  </style>
  <script type="text/javascript">
    function $$(id){
      return document.getElementById(id);
    }
    function pageLoad(){
      var can = $$(&#39;can&#39;);
      var cans = can.getContext(&#39;2d&#39;);
      cans.moveTo(20,30);//第一个起点
      cans.lineTo(120,90);//第二个点
      cans.lineTo(220,60);//第三个点(以第二个点为起点)
      cans.lineWidth=3;
      cans.strokeStyle = &#39;red&#39;;
      cans.stroke();
    }
  </script>
  <body onload="pageLoad();">
    <canvas id="can" width="400px" height="300px">4</canvas>
  </body>
</html>

여기에서 사용된 두 가지 API 메소드인 moveTo와 lineTo는 각각 선분의 시작 좌표와 끝 좌표이며, 변수는 다음과 같습니다. (X 좌표, Y 좌표), 스트로크 스타일 및 스트로크는 각각 경로 그리기 스타일 및 그리기 경로입니다.

2. 그라데이션 선 그리기

그라디언트 선은 색상에 그라데이션 효과를 줍니다. 물론 그라데이션 스타일은 경로 방향을 따를 수도 있고 그렇지 않을 수도 있습니다.

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <style type="text/css">
    canvas{border:dashed 2px #CCC}
  </style>
  <script type="text/javascript">
    function $$(id){
      return document.getElementById(id);
    }
    function pageLoad(){
      var can = $$(&#39;can&#39;);
      var cans = can.getContext(&#39;2d&#39;);
      cans.moveTo(0,0);
      cans.lineTo(400,300);
      var gnt1 = cans.createLinearGradient(0,0,400,300);//线性渐变的起止坐标
      gnt1.addColorStop(0,&#39;red&#39;);//创建渐变的开始颜色,0表示偏移量,个人理解为直线上的相对位置,最大为1,一个渐变中可以写任意个渐变颜色
      gnt1.addColorStop(1,&#39;yellow&#39;);
      cans.lineWidth=3;
      cans.strokeStyle = gnt1;
      cans.stroke();
    }
  </script>
  <body onload="pageLoad();">
    <canvas id="can" width="400px" height="300px">4</canvas>
  </body>
</html>

3. 직사각형 또는 정사각형:

이런 직사각형 상자는 HTML4를 사용하는 경우에만 배경 코드를 사용하여 생성할 수 있습니다. 이제 HTML5에서 제공하는 Canvas 기능을 쉽게 그릴 수 있으므로 HTML5의 우수성이 상당히 높습니다.

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <style type="text/css">
    canvas{border:dashed 2px #CCC}
  </style>
  <script type="text/javascript">
    function $$(id){
      return document.getElementById(id);
    }
    function pageLoad(){
      var can = $$(&#39;can&#39;);
      var cans = can.getContext(&#39;2d&#39;);
      cans.fillStyle = &#39;yellow&#39;;
      cans.fillRect(30,30,340,240);
    }
  </script>
  <body onload="pageLoad();">
    <canvas id="can" width="400px" height="300px">4</canvas>
  </body>
</html>

여기에서는 fillRect() 메서드가 사용됩니다. 문자 그대로의 의미로 보면 이것이 직사각형을 채우는 것임을 알 수 있습니다. 여기서 매개변수는 설명할 가치가 있습니다. ), 이는 수학에서와 동일합니다. 자세한 내용은

을 참조하세요. 여기서 X와 Y는 캔버스의 왼쪽 상단을 기준으로 시작됩니다. !

4. 간단한 직사각형 상자 그리기

위의 예에서는 직사각형 블록을 그리고 색상을 채우는 것에 대해 설명합니다. 이 예에서는 채우기 효과를 구현하지 않고 단순히 직사각형을 그립니다.

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <style type="text/css">
    canvas{border:dashed 2px #CCC}
  </style>
  <script type="text/javascript">
    function $$(id){
      return document.getElementById(id);
    }
    function pageLoad(){
      var can = $$(&#39;can&#39;);
      var cans = can.getContext(&#39;2d&#39;);
      cans.strokeStyle = &#39;red&#39;;
      cans.strokeRect(30,30,340,240);
    }
  </script>
  <body onload="pageLoad();">
    <canvas id="can" width="400px" height="300px">4</canvas>
  </body>
</html>

위의 예와 마찬가지로 채우기를 획으로 바꾸는 것은 매우 간단합니다. 자세한 내용은 위의 예를 참조하세요.

5. 선형 그라데이션 직사각형 그리기

그라디언트는 예제 2와 예제 3을 결합하면 그라데이션 직사각형을 만들 수 있습니다.

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <style type="text/css">
    canvas{border:dashed 2px #CCC}
  </style>
  <script type="text/javascript">
    function $$(id){
      return document.getElementById(id);
    }
    function pageLoad(){
      var can = $$(&#39;can&#39;);
      var cans = can.getContext(&#39;2d&#39;);
      var gnt1 = cans.createLinearGradient(10,0,390,0);
      gnt1.addColorStop(0,&#39;red&#39;);
      gnt1.addColorStop(0.5,&#39;green&#39;);
      gnt1.addColorStop(1,&#39;blue&#39;);
      cans.fillStyle = gnt1;
      cans.fillRect(10,10,380,280);
    }
  </script>
  <body onload="pageLoad();">
    <canvas id="can" width="400px" height="300px">4</canvas>
  </body>
</html>

아니요. fillRect(X,Y,너비,높이).

6. 원 채우기

원은 널리 사용되며 물론 타원도 포함됩니다.

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <style type="text/css">
    canvas{border:dashed 2px #CCC}
  </style>
  <script type="text/javascript">
    function $$(id){
      return document.getElementById(id);
    }
    function pageLoad(){
      var can = $$(&#39;can&#39;);
      var cans = can.getContext(&#39;2d&#39;);
      cans.beginPath();
      cans.arc(200,150,100,0,Math.PI*2,true);
      cans.closePath();
      cans.fillStyle = &#39;green&#39;;//本来这里最初使用的是red,截图一看,傻眼了,怕上街被爱国者打啊,其实你懂的~~
      cans.fill();
    }
  </script>
  <body onload="pageLoad();">
    <canvas id="can" width="400px" height="300px">4</canvas>
  </body>
</html>

여기서 호 방법의 사용법은 arc(X,Y,Radius,startAngle,endAngle,anticlockwise)입니다. 이는 (중심 X 좌표, 중심 Y 좌표, 반경, 시작 각도(라디안)을 의미합니다. , 끝 각도 라디안, 시계 방향으로 그릴지 여부);

arc의 매개변수 비교:

a, cans.arc(200,150,100,0,Math.PI,true);

c, cans.arc(200,150,100 , 0,Math.PI/2,true);[/code]

c、cans.arc(200,150,100,0,Math.PI/2,true);

d、cans.arc( 200,150,100,0,Math.PI/2,false);

7, Circular block

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <style type="text/css">
    canvas{border:dashed 2px #CCC}
  </style>
  <script type="text/javascript">
    function $$(id){
      return document.getElementById(id);
    }
    function pageLoad(){
      var can = $$(&#39;can&#39;);
      var cans = can.getContext(&#39;2d&#39;);
      cans.beginPath();
      cans.arc(200,150,100,0,Math.PI*2,false);
      cans.closePath();
      cans.lineWidth = 5;
      cans.strokeStyle = &#39;red&#39;;
      cans.stroke();
    }
  </script>
  <body onload="pageLoad();">
    <canvas id="can" width="400px" height="300px">4</canvas>
  </body>
</html>

여기에서는 설명하지 않겠습니다. lineWidth는 선의 너비를 제어합니다.

8. 원형 그라데이션

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <style type="text/css">
    canvas{border:dashed 2px #CCC}
  </style>
  <script type="text/javascript">
    function $$(id){
      return document.getElementById(id);
    }
    function pageLoad(){
      var can = $$(&#39;can&#39;);
      var cans = can.getContext(&#39;2d&#39;);
      var gnt = cans.createRadialGradient(200,300,50,200,200,200);
      gnt.addColorStop(1,&#39;red&#39;);
      gnt.addColorStop(0,&#39;green&#39;);
      cans.fillStyle = gnt;
      cans.fillRect(0,0,800,600);
    }
  </script>
  <body onload="pageLoad();">
    <canvas id="can" width="800px" height="600px">4</canvas>
  </body>
</html>

여기서 설명해야 할 것은 createRadialGradient 메소드이며, 매개변수는 (Xstart, Ystart, radiusStart, XEnd, YEnd, radiusEnd)입니다. 즉, 그라디언트를 구현할 때 두 개의 원을 사용합니다. 하나는 원래 원이고 다른 하나는 그라디언트 원입니다. 실제로 이 좌표 및 반경 제어 방법은

3차원 원

과 같은 다양한 스타일을 구현할 수 있습니다.

var gnt = cans.createRadialGradient(200,150,0,200,50,250);
gnt.addColorStop(0,&#39;red&#39;);
gnt.addColorStop(1,&#39;#333&#39;);

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

JavaScript和html5 canvas如何绘制一个小人的代码

使用JavaScript和canvas实现图片的裁剪

위 내용은 JavaScript는 Canvas를 사용하여 그리기 그래픽을 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.