Tracking graphic pen properties live

I am making some experiments and I want to be able to draw in Blender (2d animation) and at the same time extracting the motion data of my graphic pen (x-axis position, y-axis position, pen pressure). I am especially interested in pressure. Do you have any coding tips or examples to help me?

Thank you for your time!

You can use a Modal Operator to do what you need.

I’ve modified the operator_modal.py template (found in the Scripting Workspace, in the Text Editor under ‘Templates > Python’) to give you a starting point:

import bpy


class ModalOperator(bpy.types.Operator):
    """Print Screen and Region Coordinates to the Console"""
    bl_idname = "object.modal_operator"
    bl_label = "Simple Modal Operator"

    def modal(self, context, event):
        if event.type == 'MOUSEMOVE':
            # This is where we get the data
            print('')
            print(f'Screen: ({event.mouse_x}, {event.mouse_y})')
            print(f'Region: ({event.mouse_region_x}, {event.mouse_region_y})')
            print(f'Pressure: {event.pressure}')

        elif event.type == 'LEFTMOUSE':
            return {'FINISHED'}

        elif event.type in {'RIGHTMOUSE', 'ESC'}:
            return {'CANCELLED'}

        return {'RUNNING_MODAL'}

    def invoke(self, context, event):
        context.window_manager.modal_handler_add(self)
        return {'RUNNING_MODAL'}


def register():
    bpy.utils.register_class(ModalOperator)


def unregister():
    bpy.utils.unregister_class(ModalOperator)


if __name__ == "__main__":
    register()

    # test call
    bpy.ops.object.modal_operator('INVOKE_DEFAULT')

A few little tricky things here:

  • it’s a Modal, which means that it runs in a loop, so your pen position (same as mouse position) will update every time you move your mouse. This is good for getting accurate data, but it floods your console with info quickly, so I printed a blank line at the top of each block to keep things separate.

  • I think you probably want to get the region coordinates, rather than the screen coordinates, but I’ve included both, and Blender has a few handy utilities to convert between the two, as well.

  • I don’t have a pen to test it, but I don’t think this will update when you change pen pressure without moving the pen, if this is a necessity it can probably be added

There is also an operator_modal_draw template that will draw the info onto the screen, rather than into the console, but I thought that might be overkill if you just wanted to get the position and pressure data.