开发者

Drawing "negative space" on HTML <canvas>

I want to draw a solid black rectangle with a circula开发者_运维百科r hole in it, with the background image visible through the hole. Is there an easy way to do that?


Draw the outside shape with a path, aka moveTo, lineTo, etc. Then draw the negative shape inside that shape, but in the opposite clockwise/anticlockwise direction. Then call fill().

Here's an example drawing a circle with a circular hole.

<html><head></head><body>
  <canvas id="canvas" width=600 height=600></canvas>
  <script type="text/javascript">
    var canvas = document.getElementById("canvas");
    var width = canvas.width, height = canvas.height;
    var context = canvas.getContext("2d");

    // draw a diagonal line just to demonstrate the transparency later
    context.beginPath();
    context.moveTo(width/2 - height/2, 0);
    context.lineTo(width/2 + height/2, height);
    context.lineWidth = 3;
    context.strokeStyle = "#0f0";
    context.stroke();

    // draw a circle with a hole in it
    context.beginPath();
    context.arc(width/2, height/2, height*3/8, 0, 2*Math.PI);
    context.arc(width/2, height/2, height*1/8, 0, 2*Math.PI, true);
    context.fillStyle = "#555";
    context.fill();
  </script>
</body>
</html>


I don't know if this is the best way, but it works on Chrome. Set

ctx.globalCompositeOperation = "xor";

Then draw the circle, and the rectangle over it. The circle will then cancel out (xor) with the rectangle and become transparent.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜