Paintable Canvas Hacks

I've been playing around with the paintable canvas quite a bit here lately for fun, and I was wondering if anybody had any cool hacks for canvas development they would be willing to share.

To start things off, I'll share a simple way to get drawn curves right in the canvas.

Edit: The gauge example below is just a component with a lot of curves. There are better and easier ways to make such a gauge with the canvas, but for the purposes of this post, the number of curves this component has makes it ideal for demonstrating this method.

A simple method for drawing perfect curves with the paintable canvas:
Using variable names that are self explanitory, the drawArc method looks like this:

g.drawArc(x, y, width, height, startingAngle, angleLengthInDegrees)

I've found that if you take the circle tool, give it a transparent background, and position it where you want the curve to be, its x, y, width and height parameters will be exactly right.

Therefore. if I wanted to make something like this custom gauge with rounded edges:
image

I could start by simply overlaying my canvas with simple shapes produced by the round shape tool to get the proper dimensions:
image

image

Then, select each shape and press ctrl-P to get the parameters:
image
In my case, the bounds for the four circles are:

[46, 221, 50, 50] # Left small circle
[204, 221, 50, 50] # Right small circle
[50, 50, 200, 200] # Large inner circle
[0, 0, 300, 300] # Large outer circle

Once this is done there will only be two parameters needed for each of the four arcs. This can be determined by simply using a unit circle:
image

It looks like my two large circles should start at about 315 degrees and end at around 225 degrees. That would be a total of 270 degrees travel, so my code would look like this:

g = event.graphics

g.drawArc(0, 0, 300, 300, 315, 270)
g.drawArc(50, 50, 200, 200, 315, 270)

Looking again at the unit circle, I can estimate that my small left circle should start at around 225 degrees and end 180 degrees later at 45 degrees. My right small circle looks like it should start at around 135 degrees, and end 180 degrees later at 315 degrees, so I'll add these lines to my code:

g.drawArc(46, 221, 50, 50, 225, 180)
g.drawArc(204, 221, 50, 50, 135, 180)

When I run preview mode, I see this in my canvas:
image

It's not perfect, but it's pretty darn close. From here, a little trial and error to tweak the numbers produces this result:
image

g = event.graphics

# Large Outer Circle
g.drawArc(0, 0, 300, 300, 310, 280)

# Large Inner Circle
g.drawArc(50, 50, 200, 199, 309, 283)

# Small Left Arc
g.drawArc(46, 221, 51, 51, 228, 180)

# Small Right Arc
g.drawArc(204, 221, 50, 50, 130, 180)
5 Likes

This is how I did it a few years ago...
GaugeArcDonutAnimation
GaugeCanvasArcDonutAnimated.zip (23.5 KB)
I'm using Arc2D.Double with g.setStroke(BasicStroke(arcwidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER)).
CAP_ROUND is for rounded ends, CAP_BUTT is for normal ends...

7 Likes

Customized Borders:
Simply fill the bottom layer of a container with a paintable canvas to create custom borders like these:
image

# Curved border
# Developed for the repaint event handler of a paintable canvas component

# Define the parent container
parent = event.source.parent

# Define a border width
borderWidth = 15

# Gradient severity
darkenPerPixel = 3

# Get graphics instance
graphics = event.graphics

# Define the unedited background color using rgba intengers
# Since the border color shifts by the amount to darken for every pixel of border width,
# ...each rgb must be at least the same integer value as the border width to ensure no integer can be calculated as less than zero.
startingRed = parent.background.red if parent.background.red >= borderWidth * darkenPerPixel else borderWidth * darkenPerPixel
startingGreen = parent.background.green if parent.background.green >= borderWidth else borderWidth * darkenPerPixel
startingBlue = parent.background.blue if parent.background.blue >= borderWidth else borderWidth * darkenPerPixel

# If any rgb values were adjusted, apply the adjusted values to the parent container's background property
startingBackground = system.gui.color(startingRed, startingGreen, startingBlue, parent.background.alpha)
if parent.background != startingBackground:
	parent.background = startingBackground

# For each side of the canvas, paint the border
for side in range(4):

	# Initialize RGB values for the border. For left and top (side 0 and 1), reduce each by borderWidth
	# For bottom and right (side 2 and 3), keep the original starting RGB values
	# Determine the start and end points for drawing lines based on the side being processed
	if side == 0 or side == 1: # Left side or Top side
		red = startingRed - borderWidth * darkenPerPixel
		green = startingGreen - borderWidth * darkenPerPixel
		blue = startingBlue - borderWidth * darkenPerPixel
		start = 0
		end = borderWidth
	else:
		red = startingRed
		green = startingGreen
		blue = startingBlue				
		if side == 3: # Right side
			start = event.source.width - borderWidth
			end = event.source.width
		else: # Bottom side
			start = event.source.height - borderWidth
			end = event.source.height
			
	# Draw the border lines, adjusting the RGB values to create a gradient effect along each side
	for pixel in range(start, end):
	
		# Increment or decrement RGB values to create a rounded fading effect on the border
		if pixel - start < borderWidth and side < 2 :
			red +=  darkenPerPixel
			green += darkenPerPixel
			blue += darkenPerPixel
		else:
			red -= darkenPerPixel
			green -= darkenPerPixel
			blue -= darkenPerPixel
			
		# Set the current color for drawing
		graphics.setColor(system.gui.color(red, green, blue))
		
		# Draw lines based on the side being processed to create the border effect
		if side == 0: # Left side
			graphics.drawLine(pixel, (0 + pixel), pixel, (event.source.height - pixel))
		elif side == 1: # Top side
			graphics.drawLine((0 + pixel), pixel, (event.source.width - pixel), pixel)
		elif side == 3: # Right side
			increment = event.source.width - pixel
			graphics.drawLine(pixel, (0 + increment), pixel, (event.source.height - increment))
		else: # Bottom side
			increment = event.source.height - pixel
			graphics.drawLine((0 + increment), pixel, (event.source.width - increment), pixel)
1 Like

That looks familiar...

This demonstrates using hit testing on the canvas to turn your gauge into a "slider" for input purposes.

Be warned in advance that there is some "fancy" math involved.

I also often find that is useful to do all of the drawing at a known unit size and then transform and/or scale to the final size at the end.

1 Like

These lines from the default component example are handy:

#### Scale graphics to actual component size
dX = (event.width-1)/100.0
dY = (event.height-1)/100.0
g.scale(dX,dY)
1 Like

On Screen Presentation Mouse:
Presentation3

I was doing a demo video for a tutorial I made about modifying a slider's click behavior, and to make the mouse clicks visible, I created a simple demo mouse with the paintable canvas. It's useful, so I'm posting the tutorial on how to create it here in case anybody else would like to use it.

First: add two custom boolean properties to the paintable canvas called leftClick and rightClick:
image

Second: Add this script to the paintable canvas's repaint event handler:

# Get the graphics object from the event
graphics = event.graphics

# Create the main body of the mouse
graphics.setColor(system.gui.color('grey'))
graphics.fillOval(40, 20, 120, 200)

# Set the button colors according to whether or not they have been clicked
# and create the buttons

# Left Button
if event.source.leftClick:
	graphics.setColor(system.gui.color('lightgreen'))
	graphics.fillArc(50, 50, 100, 60, 90, 180)
	
else:
	graphics.setColor(system.gui.color('lightgrey'))
graphics.fillArc(50, 50, 100, 60, 90, 180)

# Right Button
if event.source.rightClick:
	graphics.setColor(system.gui.color('lightgreen'))
	graphics.fillArc(50, 50, 100, 60, 270, 180)

else:
	graphics.setColor(system.gui.color('lightgrey'))
graphics.fillArc(50, 50, 100, 60, 270, 180)

graphics.setColor(system.gui.color('black'))
#Draw a centerline between the buttons
graphics.drawLine(100, 50, 100, 110)

# Create a center mouse wheel
graphics.setColor(system.gui.color('grey'))
graphics.fillOval(95, 65, 10, 30)

# Create a shadow around the buttons when they are clicked,
# ...to create a depressed effect
if event.source.leftClick:
	graphics.setColor(system.gui.color('black'))
	graphics.drawArc(50, 50, 100, 60, 90, 180)
if event.source.rightClick:
	graphics.setColor(system.gui.color('black'))
	graphics.drawArc(50, 50, 100, 60, 270, 180)

Finally: On the component that is being clicked on for the demonstration, add this script to the mousePressed event handler:

if event.button == 1: # left click
	event.source.parent.getComponent('Paintable Canvas').leftClick = True
elif event.button == 3: # right click
	event.source.parent.getComponent('Paintable Canvas').rightClick = True

...and add this script to the same component's mouseReleased event handler:

if event.button == 1:
	event.source.parent.getComponent('Paintable Canvas').leftClick = False
elif event.button == 3:
	event.source.parent.getComponent('Paintable Canvas').rightClick = False

Gaming Applications:

I was showing off the paintable canvas to my son and simultaneous showing him some practical applications for the vector math he was studying in trigonometry class. Things probably got a little carried away, and Bananas! was born. The whole game is rendered by a single paintable canvas, so there are a lot of cool hacks in there: slider controls, switches, buttons, animations, etc.

I had already constructed some of the ground work this a couple of years ago when I made this post:

That code includes moving dynamically created shapes around inside a canvas with a mouse, and it has various animation concepts such as momentum, reflection, etc.

5 Likes

Keyboard Controls:

It's possible that some wouldn't find this intuitive because simply typing code into the key event handlers for the paintable canvas doesn't work. To enable the controls, the paintable canvas has to be given focus first. An easy and intuitive way to accomplish this is to simply add event.source.requestFocusInWindow() to the mouse clicked event handler. Then, the key event handlers will work once the canvas has been clicked on.

Example keyPressed script:

# A timer component could be started with the keyPressed event handler
# ...to conduct sustained repetative presses when a key is held down,
# ...and the key released event handler would stop and reset the timer.

if event.keyCode == event.VK_UP:
	print 'UP'
elif event.keyCode == event.VK_DOWN:
	print 'DOWN'
elif event.keyCode == event.VK_ENTER:
	print 'ENTER'
elif event.keyCode == event.VK_RIGHT:
	print 'RIGHT'
elif event.keyCode == event.VK_LEFT:
	print 'LEFT'

Edit/Additional information:
When painting controls in the canvas, a focus traversal policy can be simulated by putting a focusable component in the container with the canvas. Use the component's focusGained event handler to simply redirect the focus back to the canvas. Inside the canvas itself, use the focusLost event handler to traverse painted controls:

if event.cause == event.cause.TRAVERSAL_FORWARD:
	# Drive simulated forward traversal here
elif event.cause == event.cause.TRAVERSAL_BACKWARD:
	# Drive simulated reverse traversal here

Note: It could seem like the requestFocusInWindow could be called directly from the focusLost event, eliminating the need for some arbitrary focusable component, but without it, there will be nothing for the real focus traversal policy to tab to, and consequently, there is no guarantee that the focusLost event will occur.

Tangibly, I'm not aware of a simple way to detect or consume the tab key events in Vision, so I imagine this approach could easily be adapted for use cases with other components where it is desirable to mute or manipulate tab actions.

Using the paintable canvas as an overlay:

PaintableCanvasFloatingOutlineDemo

1 Like

Below is a master list of all possible string arguments for system.gui.color() assigned to a variable for use in scripting functions. I originally created this for the random confetti generator I developed for BANANAS Version 2, but it's been coming in quite handy elsewhere, so I'm posting it here:

possibleStringColors = [
	#String,					#Hex				#RGB
	'AliceBlue', #				#F0F8FF				(240, 248, 255)
	'AntiqueWhite', #			#FAEBD7				(250, 235, 215)
	'Aqua', #					#00FFFF				(0, 255, 255)
	'Aquamarine', #				#7FFFD4				(127, 255, 212)
	'Azure', #					#F0FFFF				(240, 255, 255)
	'Beige', #					#F5F5DC				(245, 245, 220)
	'Bisque', #					#FFE4C4				(255, 228, 196)
	'Black', #					#000000				(0, 0, 0)
	'BlanchedAlmond', #			#FFEBCD				(255, 235, 205)
	'Blue', #					#0000FF				(0, 0, 255)
	'BlueViolet', #				#8A2BE2				(138, 43, 226)
	'Brown', #					#A52A2A				(165, 42, 42)
	'BurlyWood', #				#DEB887				(222, 184, 135)
	'CadetBlue', #				#5F9EA0				(95, 158, 160)
	'Chartreuse', #				#7FFF00				(127, 255, 0)
	'Chocolate', #				#D2691E				(210, 105, 30)
	'Clear', #					#FFFFFF				(255, 255, 255, 0)
	'Coral', #					#FF7F50				(255, 127, 80)
	'CornflowerBlue', #			#6495ED				(100, 149, 237)
	'Cornsilk', #				#FFF8DC				(255, 248, 220)
	'Crimson', #				#DC143C				(220, 20, 60)
	'Cyan', #					#00FFFF				(0, 255, 255)
	'DarkBlue', #				#00008B				(0, 0, 139)
	'DarkCyan', #				#008B8B				(0, 139, 139)
	'DarkGoldenRod', #			#B8860B				(184, 134, 11)
	'DarkGrey', #				#A9A9A9				(169, 169, 169)
	'DarkGreen', #				#006400				(0, 100, 0)
	'DarkKhaki', #				#BDB76B				(189, 183, 107)
	'DarkMagenta', #			#8B008B				(139, 0, 139)
	'DarkOliveGreen', #			#556B2F				(85, 107, 47)
	'Darkorange', #				#FF8C00				(255, 140, 0)
	'DarkOrchid', #				#9932CC				(153, 50, 204)
	'DarkRed', #				#8B0000				(139, 0, 0)
	'DarkSalmon', #				#E9967A				(233, 150, 122)
	'DarkSeaGreen', #			#8FBC8F				(143, 188, 143)
	'DarkSlateBlue', #			#483D8B				(72, 61, 139)
	'DarkSlateGrey', #			#2F4F4F				(47, 79, 79)
	'DarkTurquoise', #			#00CED1				(0, 206, 209)
	'DarkViolet', #				#9400D3				(148, 0, 211)
	'DeepPink', #				#FF1493				(255, 20, 147)
	'DeepSkyBlue', #			#00BFFF				(0, 191, 255)
	'DimGrey', #				#696969				(105, 105, 105)
	'DodgerBlue', #				#1E90FF				(30, 144, 255)
	'Feldspar', #				#D19275				(209, 146, 117)
	'FireBrick', #				#B22222				(178, 34, 34)
	'FloralWhite', #			#FFFAF0				(255, 250, 240)
	'ForestGreen', #			#228B22				(34, 139, 34)
	'Fuchsia', #				#FF00FF				(255, 0, 255)
	'Gainsboro', #				#DCDCDC				(220, 220, 220)
	'GhostWhite', #				#F8F8FF				(248, 248, 255)
	'Gold', #					#FFD700				(255, 215, 0)
	'GoldenRod', #				#DAA520				(218, 165, 32)
	'Grey', #					#808080				(128, 128, 128)
	'Green', #					#008000				(0, 128, 0)
	'GreenYellow', #			#ADFF2F				(173, 255, 47)
	'HoneyDew', #				#F0FFF0				(240, 255, 240)
	'HotPink', #				#FF69B4				(255, 105, 180)
	'IndianRed', #				#CD5C5C				(205, 92, 92)
	'Indigo', #					#4B0082				(75, 0, 130)
	'Ivory', #					#FFFFF0				(255, 255, 240)
	'Khaki', #					#F0E68C				(240, 230, 140)
	'Lavender', #				#E6E6FA				(230, 230, 250)
	'LavenderBlush', #			#FFF0F5				(255, 240, 245)
	'LawnGreen', #				#7CFC00				(124, 252, 0)
	'LemonChiffon', #			#FFFACD				(255, 250, 205)
	'LightBlue', #				#ADD8E6				(173, 216, 230)
	'LightCoral', #				#F08080				(240, 128, 128)
	'LightCyan', #				#E0FFFF				(224, 255, 255)
	'LightGoldenRodYellow', #	#FAFAD2				(250, 250, 210)
	'LightGreen', #				#90EE90				(144, 238, 144)
	'LightGrey', #				#D3D3D3				(211, 211, 211)
	'LightPink', #				#FFB6C1				(255, 182, 193)
	'LightSalmon', #			#FFA07A				(255, 160, 122)
	'LightSeaGreen', #			#20B2AA				(32, 178, 170)
	'LightSkyBlue', #			#87CEFA				(135, 206, 250)
	'LightSlateBlue', #			#8470FF				(132, 112, 255)
	'LightSlateGrey', #			#778899				(119, 136, 153)
	'LightSteelBlue', #			#B0C4DE				(176, 196, 222)
	'LightYellow', #			#FFFFE0				(255, 255, 224)
	'Lime', #					#00FF00				(0, 255, 0)
	'LimeGreen', #				#32CD32				(50, 205, 50)
	'Linen', #					#FAF0E6				(250, 240, 230)
	'Magenta', #				#FF00FF				(255, 0, 255)
	'Maroon', #					#800000				(128, 0, 0)
	'MediumAquaMarine', #		#66CDAA				(102, 205, 170)
	'MediumBlue', #				#0000CD				(0, 0, 205)
	'MediumOrchid', #			#BA55D3				(186, 85, 211)
	'MediumPurple', #			#9370DB				(147, 112, 219)
	'MediumSeaGreen', #			#3CB371				(60, 179, 113)
	'MediumSlateBlue', #		#7B68EE				(123, 104, 238)
	'MediumSpringGreen', #		#00FA9A				(0, 250, 154)
	'MediumTurquoise', #		#48D1CC				(72, 209, 204)
	'MediumVioletRed', #		#C71585				(199, 21, 133)
	'MidnightBlue', #			#191970				(25, 25, 112)
	'MintCream', #				#F5FFFA				(245, 255, 250)
	'MistyRose', #				#FFE4E1				(255, 228, 225)
	'Moccasin', #				#FFE4B5				(255, 228, 181)
	'NavajoWhite', #			#FFDEAD				(255, 222, 173)
	'Navy', #					#000080				(0, 0, 128)
	'OldLace', #				#FDF5E6				(253, 245, 230)
	'Olive', #					#808000				(128, 128, 0)
	'OliveDrab', #				#6B8E23				(107, 142, 35)
	'Orange', #					#FFA500				(255, 165, 0)
	'OrangeRed', #				#FF4500				(255, 69, 0)
	'Orchid', #					#DA70D6				(218, 112, 214)
	'PaleGoldenRod', #			#EEE8AA				(238, 232, 170)
	'PaleGreen', #				#98FB98				(152, 251, 152)
	'PaleTurquoise', #			#AFEEEE				(175, 238, 238)
	'PaleVioletRed', #			#DB7093				(219, 112, 147)
	'PapayaWhip', #				#FFEFD5				(255, 239, 213)
	'PeachPuff', #				#FFDAB9				(255, 218, 185)
	'Peru', #					#CD853F				(205, 133, 63)
	'Pink', #					#FFC0CB				(255, 192, 203)
	'Plum', #					#DDA0DD				(221, 160, 221)
	'PowderBlue', #				#B0E0E6				(176, 224, 230)
	'Purple', #					#800080				(128, 0, 128)
	'Red', #					#FF0000				(255, 0, 0)
	'RosyBrown', #				#BC8F8F				(188, 143, 143)
	'RoyalBlue', #				#4169E1				(65, 105, 225)
	'SaddleBrown', #			#8B4513				(139, 69, 19)
	'Salmon', #					#FA8072				(250, 128, 114)
	'SandyBrown', #				#F4A460				(244, 164, 96)
	'SeaGreen', #				#2E8B57				(46, 139, 87)
	'SeaShell', #				#FFF5EE				(255, 245, 238)
	'Sienna', #					#A0522D				(160, 82, 45)
	'Silver', #					#C0C0C0				(192, 192, 192)
	'SkyBlue', #				#87CEEB				(135, 206, 235)
	'SlateBlue', #				#6A5ACD				(106, 90, 205)
	'SlateGrey', #				#708090				(112, 128, 144)
	'Snow', #					#FFFAFA				(255, 250, 250)
	'SpringGreen', #			#00FF7F				(0, 255, 127)
	'SteelBlue', #				#4682B4				(70, 130, 180)
	'Tan', #					#D2B48C				(210, 180, 140)
	'Teal', #					#008080				(0, 128, 128)
	'Thistle', #				#D8BFD8				(216, 191, 216)
	'Tomato', #					#FF6347				(255, 99, 71)
	'Transparent', #			#FFFFFF				(255, 255, 255, 0)
	'Turquoise', #				#40E0D0				(64, 224, 208)
	'Violet', #					#EE82EE				(238, 130, 238)
	'VioletRed', #				#D02090				(208, 32, 144)
	'Wheat', #					#F5DEB3				(245, 222, 179)
	'White', #					#FFFFFF				(255, 255, 255)
	'WhiteSmoke', #				#F5F5F5				(245, 245, 245)
	'Yellow', #					#FFFF00				(255, 255, 0)
	'YellowGreen' #				#9ACD32				(154, 205, 50)
		]
3 Likes