Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

305
Vistas
Canvas rendering from component is not working on Svelte

I'm trying to render canvas and draw rectangle on it using svelte.js, but it does not work if I write rendering code on the component side.

Here is the reproduction REPL.

It works if I move entire code in Canvas.svelte to app.svelte.

App.svelte:

<script>
    import Canvas from './Canvas.svelte';
</script>

<Canvas/>

Canvas.svelte:

<script>
  import { onMount } from 'svelte';

  let canvasEl;

  const canvas = {
    width: 1000,
    height: 1000
  };

  const drawRect = (context) => {
    context.beginPath();
    context.fillStyle = '#000000';
    context.rect(0, 0, 40, 10);
    context.fill();
  };

  onMount(() => {
    console.log('Onmount');
    const context = canvasEl.getContext('2d');
    canvas.width = document.body.clientWidth;
    canvas.height = document.body.clientHeight;
    drawRect(context);
  });
</script>

<canvas bind:this={canvasEl} width={canvas.width} height={canvas.height} />

Does anyone know the solution?

Thank you,

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Didn't find a reason of error, but found the source:

onMount(() => {
    //...
    // this 2 lines cause silent error
    canvas.width = document.body.clientWidth;
    canvas.height = document.body.clientHeight;
    //...
  });

Remove them and you will see the canvas and rect

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda