In a 2D canvas, is there a way to give a sprite an outline?

前端 未结 3 575
刺人心
刺人心 2020-12-04 03:40

I\'d like to give a sprite an outline when the character gets healed/damaged/whatever but I can\'t think of a way to code this using the 2d canvas. If it were possible, I\'

3条回答
  •  感动是毒
    2020-12-04 04:14

    • Just draw your original image in 8 position around the original image
    • Change composite mode to source-in and fill with the outline color
    • Change composite mode back to source-over and draw in the original image at correct location

    This will create a clean sharp outline with equal border thickness on every side. It is not so suited for thick outlines however. Image drawing is fast, especially when image is not scaled so performance is not an issues unless you need to draw a bunch (which in that case you would cache the drawings or use a sprite-sheet anyways).

    Example:

    var ctx = canvas.getContext('2d'),
        img = new Image;
    
    img.onload = draw;
    img.src = "http://i.stack.imgur.com/UFBxY.png";
    
    function draw() {
    
      var dArr = [-1,-1, 0,-1, 1,-1, -1,0, 1,0, -1,1, 0,1, 1,1], // offset array
          s = 2,  // scale
          i = 0,  // iterator
          x = 5,  // final position
          y = 5;
      
      // draw images at offsets from the array scaled by s
      for(; i < dArr.length; i += 2)
        ctx.drawImage(img, x + dArr[i]*s, y + dArr[i+1]*s);
      
      // fill with color
      ctx.globalCompositeOperation = "source-in";
      ctx.fillStyle = "red";
      ctx.fillRect(0,0,canvas.width, canvas.height);
      
      // draw original image in normal mode
      ctx.globalCompositeOperation = "source-over";
      ctx.drawImage(img, x, y);
    }

提交回复
热议问题