Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

306
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!