Hammerspoon / hammerspoon

Staggeringly powerful macOS desktop automation with Lua
http://www.hammerspoon.org
MIT License
12.01k stars 583 forks source link

Add some hs.canvas examples to Getting Started Guide #1331

Open cmsj opened 7 years ago

cmsj commented 7 years ago

@asmagill I'm not sure if I'm being super dumb here, but I can't for the life of me figure out how hs.canvas works :/

I'm trying to draw a black square, with part of it clipped away by a circle - so the square is {x=0,y=0,w=22,h=22} and filled black, then the circle should have {radius=22,center={x=22,y=22}} and delete the parts of the square it overlaps.

I think we might need to work up some simpler, more progressive examples for hs.canvas and put them in the GSG.

asmagill commented 7 years ago

Yeah, clipping is annoying to wrap your head around... If you have any suggestions for documentation or examples I'll happy to add them to the wiki page already linked to in the hs.canvas documentation or we could setup it's own section in the Hammerspoon wiki at some point.

To get at what I think you're trying to do, try this:

a = hs.canvas.new{x = 100, y = 100, h = 200, w = 200}
-- clipping is annoying... it's easiest (for me) to think of it this way:
-- we're telling the *following* shapes where they can actually show content.
-- so...
a[#a+1] = {             -- first we start with the entire frame as being available
    action = "build", 
    type = "rectangle",
}
a[#a+1] = {             -- but we take out a circle (note the reversePath)
    type = "circle",
    center = { x = 22, y = 22 },
    radius = 22,
    reversePath = true,
    action = "clip",
}
a[#a+1] = {             -- *NOW* we can draw our actual "visible" parts
    type = "rectangle",
    frame = { x = 0, y = 0, h = 22, w = 22},
    fillColor = { alpha = 1 },
    action = "fill",
}
a[#a+1] = {             -- so future objects aren't clipped by the circle
    type = "resetClip"
}
a:show()
-- a[1] could just as easily have been a rectangle of the same size as a[3];
-- we just need it as something for a[2] to "cut out" of.

It took a lot of reviewing and re-reviewing the docs at https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CocoaDrawingGuide/GraphicsContexts/GraphicsContexts.html#//apple_ref/doc/uid/TP40003290-CH203-BCIIADBC (and other sections of this as well) before I sort of understood it enough to get canvas off the ground.

cmsj commented 7 years ago

@asmagill thanks, that does indeed do what I'm looking for, and i think I understand the clipping stuff a bit better now :)

I'll leave this issue open for when ideas strike about possible simple examples we could document.