clearing circular regions from HTML5 Canvas

后端 未结 6 1055
耶瑟儿~
耶瑟儿~ 2020-11-30 01:37

It appears the only way to clear a region from a canvas is to use the clearRect() command - I need to clear a circle (I am masking out areas from a filled canvas, point ligh

6条回答
  •  时光取名叫无心
    2020-11-30 02:23

    If you're making a game or something where squeezing every bit of performance matters, have a look at how I made this answer: Canvas - Fill a rectangle in all areas that are fully transparent

    Specifically, the edit of the answer that leads to this: http://jsfiddle.net/a2Age/2/

    The huge plusses here:

    • No use of paths (slow)
    • No use of clips (slow)
    • No need for save/restore (since there's no way to reset a clipping region without clearing all state(1), it means you must use save/restore also)

    (1) I actually complained about this and resetClip() has been put in the offical spec because of it, but it will be a while before browsers implement it.

    Code

    var ctx          = document.getElementById('canvas1').getContext('2d'),
        ambientLight = 0.1,
        intensity    = 1,
        radius       = 100,
        amb          = 'rgba(0,0,0,' + (1 - ambientLight) + ')';
    
    addLight(ctx, intensity, amb, 200, 200, 0, 200, 200, radius); // First circle
    addLight(ctx, intensity, amb, 250, 270, 0, 250, 270, radius); // Second circle
    addLight(ctx, intensity, amb, 50, 370, 0, 50, 370, radius, 50); // Third!
    
    ctx.fillStyle = amb;
    ctx.globalCompositeOperation = 'xor';
    ctx.fillRect(0, 0, 500, 500);
    
    function addLight(ctx, intsy, amb, xStart, yStart, rStart, xEnd, yEnd, rEnd, xOff, yOff) {
      xOff = xOff || 0;
      yOff = yOff || 0;
    
      var g = ctx.createRadialGradient(xStart, yStart, rStart, xEnd, yEnd, rEnd);
      g.addColorStop(1, 'rgba(0,0,0,' + (1 - intsy) + ')');
      g.addColorStop(0, amb);
      ctx.fillStyle = g;
      ctx.fillRect(xStart - rEnd + xOff, yStart - rEnd + yOff, xEnd + rEnd, yEnd + rEnd);
    }
    canvas {
      border: 1px solid black;
      background-image: url('http://placekitten.com/500/500');
    }

提交回复
热议问题