Here's an example of how you can create the canonical URL in a custom layout handler in Magento 2:
Create or edit your custom layout XML file. This file should be located in your theme's app/design/frontend/{Vendor}/{Theme}/Magento_Theme/layout directory.
In the layout XML file, define your custom layout handler and use the block to set the canonical URL. Replace {Vendor} and {Theme} with your actual vendor and theme names.
app/design/frontend/{Vendor}/{Theme}/Magento_Theme/layout/{custom_layout}.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<!-- Your custom layout handler -->
<referenceContainer name="head">
<block class="Magento\Framework\View\Element\Text" name="custom_canonical" as="custom_canonical" before="-">
<arguments>
<argument name="text" xsi:type="string"><![CDATA[<link rel="canonical" src="{your_custom_canonical_url}" />]]></argument>
</arguments>
</block>
</referenceContainer>
</body>
</page>
Replace {custom_layout} with the name of your custom layout handler.
Replace {your_custom_canonical_url} with the desired canonical URL you want to set for the page.
Clear the Magento cache after making changes to your layout XML files.