Copy CANVAS with background image to an image

Asked

Viewed 71 times

1

I have a CANVAS in which I put a background image and on top of that image I do some drawings. Then I need to transform this CANVAS into an image, I used the commands below to make the copy but the background image is not copied. Is there any way to fix it ??

Grateful for the help.

<div id="imagens">
                <canvas id="canvas" class="ml-5 mt-2" runat="server" width="650" height="650"  style="border: 1px solid black; background-size: contain; background-repeat: no-repeat;"></canvas>
           </div>
        <img id="imagem" width="650" height="650" />

I’m using this script to make the copy

<script>var data = canvas.toDataURL();
    imagem.setAttribute('src', data);</script>

Code suggested by Japontium..

 var Img = new Image();
    Img.src = "url('http://www.digiplay.net.br/imagens/modelo2.jpg')";
    $0.getContext('2d').drawImage(Img, 0, 0, 650, 650); <== erro nesta linha
    $0.src = canvas.toDataURL('image/png', 1);
    imagem.setAttribute('src', $0);

1 answer

0

The background does not count as given when using toDataURL(), so you need to add the image to the canvas via Drawimage.

var Img=new Image();
Img.src='<link da sua imagem>';
document.getElementById('canvas').getContext('2d').drawImage(Img,0,0,650,650)
document.getElementById('imagem').src=canvas.toDataURL('image/png',1)

EDIT: I think it’s right now

  • 1

    Ola Japôncio... I put the code you suggested but there is this error (Referenceerror: $0 is not defined) see above how my code was..

  • Oh yes, you’re right, my mistake, I’ll edit the comment to be correct

Browser other questions tagged

You are not signed in. Login or sign up in order to post.