S
S
s243442018-09-01 09:54:13
JavaScript
s24344, 2018-09-01 09:54:13

How to correctly add a dynamically created image to the canvas?

Hello. Please help me solve the following problem. In an application written in Vue.js, I create an img, then I try to add it to the canvas, but it doesn't work out for me. Tell me what I'm doing wrong.

<template>
    <div>
        <canvas id="supercanvas" ref="supercanvas" width="800" height="600"></canvas>
    </div>
</template>
<script>
export default {
  mounted: function() {
    const canvas = this.$refs.supercanvas;
    const ctx = canvas.getContext('2d');

    const img = new Image();

    img.src = '../assets/1.jpg';

    let i = 0;
    function draw () {
      i++;

      ctx.clearRect(0, 0, 800, 600);

      ctx.drawImage(img, 0, 0, 800, 600);

      window.requestAnimationFrame(draw);
    }
    draw();
  }
}
</script>

(Network does not indicate jpeg, but text/html)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-09-01
@s24344

Network does not indicate jpeg, but text / html

The path is wrong. Or the server does not give the file. You should see what's in that text/html - it should be written.
Well, why is requestAnimationFrame here - I have no idea. Looks badass. There is an onload handler - draw in it:
img.onload = function() {
  ctx.drawImage(this, 0, 0, 800, 600);
};

https://jsfiddle.net/bd0ro2yL/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question