How to use Vue refs for HTML5 Canvas with Composition API and TypeScript
Jelle de Vries
I find Vue's Composition API amazing. I'm using it for all new projects, as well as building new components in old projects, because the Composition API and the Options API can be used interoperable.
TypeScript and Vue's Composition API go together really well and typing is breeze. With the Options API I often spent hours trying to figure out how to type things.
Currently I'm working on a Vue project that uses HTML5 Canvas. This article outlines how you can integrate HTML5 Canvas in your Vue component with full TypeScript support. Works like a charm!
Typing a template ref for a HTML5 Canvas element
The snippet below shows exactly how to reference a HTML5 Canvas element when using refs with the Composition API.
<template>
<canvas ref="canvasElement" width="200" height="200"/>
</template>
<script setup lang="ts">
import {onMounted, Ref, ref} from "vue";
// The important part: the name of the variable needs to be equal to the ref's name of the canvas element in the template
const canvasElement: Ref<HTMLCanvasElement | undefined> = ref();
const context: Ref<CanvasRenderingContext2D | undefined> = ref();
onMounted(() => {
// Get canvas context. If 'getContext' returns 'null', set to 'undefined', so that it conforms to the Ref typing
context.value = canvasElement.value?.getContext('2d') || undefined;
render();
});
function render() {
if (!context.value) {
return;
}
context.value.fillText('jelledev.com', 50, 50);
}
</script>