@nkochnevss

В чём причина «Uncaught TypeError: Cannot read properties of null (reading 'getContext')»?

Видел много видео и статей на подобие как сделать paint в html форме, но я хочу сделать это во vue и все никак не могу разобраться.
Код ниже написан в файле page, который импортируется в app.vue.
Возникает ошибка:

Uncaught TypeError: Cannot read properties of null (reading 'getContext')


<canvas id="myCanvas" class="signature" width="900" height="600"></canvas>

var canvas = document.getElementById("myCanvas"); 
	var context = canvas.getContext("2d");

	canvas.onmousedown = function (){
		canvas.onmousemove = function (event){
			var x = event.offsetX;
			var y = event.offsetY;
			context.fillRect(x-5, y-5, 5, 5);
		}
		canvas.onmouseup = function (){
			canvas.onmousemove = null;
		}
	}
  • Вопрос задан
  • 277 просмотров
Решения вопроса 1
modelair
@modelair
unsocial
<script setup>
onMounted(() => {
    let canvas= document.getElementById("myCanvas") 
    let context = canvas?.getContext("2d")
    canvas.onmousedown = function (){
        canvas.onmousemove = function (event){
            let x = event.offsetX
            let y = event.offsetY
            context.fillRect(x-5, y-5, 5, 5)
        }
        canvas.onmouseup = function (){
            canvas.onmousemove = null
        }
    }
})
</script>


вообще такой код пишется проще:
<canvas 
    @mousedown="canvasMouseDowned = true"
    @mousemove="canvasMouseMove"
    @mouseup="canvasMouseDowned = false"
     class="signature"
     width="900"
     height="600"
/>

<script setup lang="ts">
const canvasMouseDowned = ref(false)

function canvasMouseMove(event: MouseEvent) {
    if (!canvasMouseDowned.value) return
    let x = event.offsetX
    let y = event.offsetY
    if (event.target) {
        let context = (event.target as HTMLCanvasElement).getContext('2d')
        context?.fillRect(x-5, y-5, 5, 5)
    }

}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы