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

Drawing transparent shapes

For applications that require shape layering, it's often desirable to work with transparencies. In this recipe, we will learn how to set shape transparencies using the global alpha composite.

Drawing transparent shapes

How to do it...

Follow these steps to draw a transparent circle on top of an opaque square:

  1. Define a 2D canvas context:
    window.onload = function(){
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
  2. Draw a rectangle:
        // draw rectangle
        context.beginPath();
        context.rect(240, 30, 130, 130);
        context.fillStyle = "blue";
        context.fill();
  3. Set the global alpha of the canvas using the globalAlpha property and draw a circle:
        // draw circle
        context.globalAlpha = 0.5; // set global alpha
        context.beginPath();
        context.arc(359, 150, 70, 0, 2 * Math.PI, false);
        context.fillStyle = "red";
        context.fill();
    }; 
  4. 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 set the opacity of a shape using the HTML5 canvas API, we can use the globalAlpha property:

context.globalAlpha=[value]

The globalAlpha property accepts any real number between 0 and 1. We can set the globalAlpha property to 1 to make shapes fully opaque, and we can set the globalAlpha property to 0 to make shapes fully transparent.

主站蜘蛛池模板: 金湖县| 原平市| 望都县| 卢龙县| 临洮县| 阳西县| 夏津县| 崇礼县| 定安县| 松阳县| 阿拉尔市| 白朗县| 永城市| 潞西市| 东乌珠穆沁旗| 清苑县| 浦城县| 华蓥市| 左云县| 舞阳县| 锦屏县| 沭阳县| 滨州市| 中牟县| 咸宁市| 章丘市| 和平县| 中卫市| 安泽县| 阿拉善盟| 德庆县| 塘沽区| 精河县| 来凤县| 颍上县| 榆树市| 汉源县| 福清市| 子洲县| 诸暨市| 刚察县|