Draw border around nontransparent part of image on canvas

前端 未结 3 1355
生来不讨喜
生来不讨喜 2020-11-28 12:41

I\'m drawing an image onto a canvas using drawImage. It\'s a PNG that is surrounded by transparent pixels, like this:

3条回答
  •  攒了一身酷
    2020-11-28 13:02

    I was looking for a way to do this and it seems there are only laborious solutions.

    I came up with a little workaround using shadows and a loop to display them all around the image:

    // Shadow color and blur
    // To get a blurry effect use rgba() with a low opacity as it will be overlaid
    context.shadowColor = "red";
    context.shadowBlur = 0;
    
    // X offset loop
    for(var x = -2; x <= 2; x++){
        // Y offset loop
        for(var y = -2; y <= 2; y++){
            // Set shadow offset
            context.shadowOffsetX = x;
            context.shadowOffsetY = y;
    
            // Draw image with shadow
            context.drawImage(img, left, top, width, height);
        }
    }
    

提交回复
热议问题