官术网_书友最值得收藏!

  • HTML5 Canvas Cookbook
  • Eric Rowell
  • 341字
  • 2021-08-27 12:08:06

Fun with Bezier curves: drawing a cloud

In this recipe, we will learn how to draw a custom shape by connecting a series of Bezier curve sub paths to create a fluffy cloud.

Fun with Bezier curves: drawing a cloud

How to do it...

Follow these steps to draw a fluffy cloud in the center of the canvas:

  1. Define a 2D canvas context:
    window.onload = function(){
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
  2. Draw a cloud by connecting six Bezier curves:
        var startX = 200;
        var startY = 100;
        
      // draw cloud shape
        context.beginPath(); 
        context.moveTo(startX, startY);
        context.bezierCurveTo(startX - 40, startY + 20, startX - 40, startY + 70, startX + 60, startY + 70);
        context.bezierCurveTo(startX + 80, startY + 100, startX + 150, startY + 100, startX + 170, startY + 70);
        context.bezierCurveTo(startX + 250, startY + 70, startX + 250, startY + 40, startX + 220, startY + 20);
        context.bezierCurveTo(startX + 260, startY - 40, startX + 200, startY - 50, startX + 170, startY - 30);
        context.bezierCurveTo(startX + 150, startY - 75, startX + 80, startY - 60, startX + 80, startY - 30);
        context.bezierCurveTo(startX + 30, startY - 75, startX - 20, startY - 60, startX, startY);
        context.closePath();
  3. Define a radial gradient with the createRadialGradient() method and fill the shape with the gradient:
      //add a radial gradient
        var grdCenterX = 260;
        var grdCenterY = 80;
        var grd = context.createRadialGradient(grdCenterX, grdCenterY, 10, grdCenterX, grdCenterY, 200);
        grd.addColorStop(0, "#8ED6FF"); // light blue
        grd.addColorStop(1, "#004CB3"); // dark blue
        context.fillStyle = grd;
        context.fill();
  4. Set the line width and stroke the cloud:
      // set the line width and stroke color
        context.lineWidth = 5;
        context.strokeStyle = "#0000ff";
        context.stroke();
    };
  5. Embed the canvas tag inside the body of the HTML document:
    <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"> 
    </canvas>

How it works...

To draw a fluffy cloud using the HTML5 canvas API, we can connect several Bezier curves to form the perimeter of the cloud shape. To create the illusion of a bulbous surface, we can create a radial gradient using the createRadialGradient() method, set the gradient colors and offsets using the addColorStop() method, set the radial gradient as the fill style using fillStyle, and then apply the gradient using fill().

主站蜘蛛池模板: 无为县| 云霄县| 台东市| 漳州市| 松江区| 宿迁市| 霍城县| 太康县| 双辽市| 罗平县| 平和县| 天祝| 全州县| 泊头市| 湘潭市| 吴堡县| 绍兴市| 崇左市| 广宗县| 罗源县| 长沙市| 黎平县| 秦皇岛市| 益阳市| 彰化市| 铜陵市| 武平县| 金山区| 宕昌县| 洛隆县| 米林县| 科尔| 马龙县| 海南省| 隆林| 东丽区| 和龙市| 嘉鱼县| 文登市| 乐业县| 乐安县|