How can I create a transparent hole in a black background using grid graphics?

I want to block out a particular square when printing a grid graphics object ("grob"). To do this you can create a mask which is black where you want to print and transparent elsewhere.

So, I need a black background, with a certain square being transparent.

My first attempt was:

library(grid)
area_to_mask <- rectGrob(width = 0.3, height = 0.3)
mask_grob <- gTree(children = gList(rectGrob(), area_to_mask))
mask_grob <- fillGrob(mask_grob, rule = "evenodd",
                      gp = gpar(col = "black", fill = "black"))
masked_grob <- rectGrob(width = 0.5, height = 0.5, 
                        gp = gpar(fill = "blue"), 
                        vp = viewport(mask = mask_grob))
grid.draw(masked_grob)

Unfortunately, on ragg devices, the fillGrob crashes R when grid.draw is called. So, I am looking for a simpler way to add a transparent "hole" to an opaque background.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.