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

Working with custom shapes and fill styles

In this recipe, we'll draw four triangles and then fill each one with a different fill style. The fill styles available with the HTML5 canvas API are color fills, linear gradients, radial gradients, and patterns.

Working with custom shapes and fill styles

How to do it...

Follow these steps to draw four triangles, one with a color fill, one with a linear gradient fill, one with a radial gradient fill, and one with a pattern fill:

  1. Create a simple function that draws a triangle:
    function drawTriangle(context, x, y, triangleWidth, triangleHeight, fillStyle){
        context.beginPath();
        context.moveTo(x, y);
        context.lineTo(x + triangleWidth / 2, y + triangleHeight);
        context.lineTo(x - triangleWidth / 2, y + triangleHeight);
        context.closePath();
        context.fillStyle = fillStyle;
        context.fill();
    }
  2. Define a 2D canvas context and set the height, width, and y position of our triangles:
    window.onload = function(){
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
        
        var grd;
        var triangleWidth = 150;
        var triangleHeight = 150;
        var triangleY = canvas.height / 2 - triangleWidth / 2;
  3. Draw a triangle using a color fill:
        // color fill (left)
        drawTriangle(context, canvas.width * 1 / 5, triangleY, triangleWidth, triangleHeight, "blue");
  4. Draw a triangle using a linear gradient fill:
        // linear gradient fill (second from left)
        grd = context.createLinearGradient(canvas.width * 2 / 5, triangleY, canvas.width * 2 / 5, triangleY + triangleHeight);
        grd.addColorStop(0, "#8ED6FF"); // light blue
        grd.addColorStop(1, "#004CB3"); // dark blue
        drawTriangle(context, canvas.width * 2 / 5, triangleY, triangleWidth, triangleHeight, grd);
  5. Draw a triangle using a radial gradient fill:
        // radial gradient fill (second from right)
        var centerX = (canvas.width * 3 / 5 +
        (canvas.width * 3 / 5 - triangleWidth / 2) +
        (canvas.width * 3 / 5 + triangleWidth / 2)) / 3;
        
        var centerY = (triangleY +
        (triangleY + triangleHeight) +
        (triangleY + triangleHeight)) / 3;
        
        grd = context.createRadialGradient(centerX, centerY, 10, centerX, centerY, 100);
        grd.addColorStop(0, "red");
        grd.addColorStop(0.17, "orange");
        grd.addColorStop(0.33, "yellow");
        grd.addColorStop(0.5, "green");
        grd.addColorStop(0.666, "blue");
        grd.addColorStop(1, "violet");
        drawTriangle(context, canvas.width * 3 / 5, triangleY, triangleWidth, triangleHeight, grd);
  6. Draw a triangle using a pattern fill:
        // pattern fill (right)
        var imageObj = new Image();
        imageObj.onload = function(){
            var pattern = context.createPattern(imageObj, "repeat");
            drawTriangle(context, canvas.width * 4 / 5, triangleY, triangleWidth, triangleHeight, pattern);
        };
        imageObj.src = "wood-pattern.png";
    }; 
  7. 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...

As you might recall from Chapter 1, we can start a new path with the beginPath() method, place our drawing cursor using moveTo(), and then draw consecutive sub paths to form a path. We can add one more step to this procedure by closing our path with the closePath() method of the canvas context to create a shape:

context.closePath();

This method essentially tells the canvas context to complete the current path by connecting the last point in the path with the start point of the path.

In the drawTriangle() method, we can begin a new path using beginPath(), position the drawing cursor using moveTo(), draw two sides of the triangle using lineTo(), and then complete the third side of the triangle with closePath().

As you can see from the preceding screenshot, the second triangle from the left is filled with a linear gradient. Linear gradients can be created with the createLinearGradient() method of the canvas context, which is defined by a start point and an end point:

var grd=context.createLinearGradient(startX,startY,endX,endY);

Next, we can set the colors of the gradient using the addColorStop() method which assigns a color value at an offset position along the gradient line from 0 to 1:

grd.addColorStop(offset,color);

Colors assigned with an offset value of 0 will be positioned at the starting point of the linear gradient, and colors assigned with an offset value of 1 will be positioned at the end point of the linear gradient. In this example, we've positioned a light blue color at the top of the triangle and a dark blue color at the bottom of the triangle.

Next up, let's cover radial gradients. The second triangle from the right is filled with a radial gradient composed of six different colors. Radial gradients can be created using the createRadialGradient() method of the canvas context, which requires a starting point, a start radius, an end point, and an end radius:

var grd=context.createRadialGradient(startX,startY,
   startRadius,endX,endY,endRadius);

Radial gradients are defined by two imaginary circles. The first imaginary circle is defined by startX, startY, and startRadius. The second imaginary circle is defined by endX, endY, and endRadius. Similarly to linear gradients, we can position colors along the radial gradient line using the addColorStop() method of the canvas context.

Finally, the fourth type of fill style available with the HTML5 canvas API is patterns. We can create a pattern object using the createPattern() method of the canvas context, which requires an image object and a repeat option:

var pattern=context.createPattern(imageObj, repeatOption);

The repeatOption can take one of the four options, repeat, repeat-x, repeat-y, and no-repeat. Unless otherwise specified, the repeatOption is defaulted to repeat. We'll cover images more in depth in Chapter 3, Working with Images and Videos.

See also...

  • Putting it all together: drawing a jet
主站蜘蛛池模板: 涿鹿县| 突泉县| 东乡| 乐山市| 河南省| 扶沟县| 云浮市| 吕梁市| 东港市| 金昌市| 泰兴市| 鹰潭市| 永泰县| 灵石县| 平和县| 斗六市| 哈密市| 晋中市| 民权县| 嘉义县| 华亭县| 江阴市| 连云港市| 汉阴县| 宜兴市| 徐汇区| 东乌珠穆沁旗| 泗水县| 郎溪县| 珠海市| 怀集县| 南华县| 库伦旗| 东港市| 肇庆市| 仁化县| 盐城市| 古丈县| 广汉市| 景泰县| 合水县|