Hi I am using canvas
for drawing but issue is this on page load I want to show an image on canvas
so the user can continue from where he left
<div id="wPaint" style="position:relative; width:100%; height:600px; background-color:white; border:1px solid black; resize: both; ">
</div>
canvas
is loaded in this div. if I inspect then canvas
code is below image
Thanks for any help.
CodePudding user response:
Introduction
The question is referring to a scenario when you have a canvas
and the user can change its content. I assume that this works and you need to be able to save the content of the canvas
as an image and load that saved image and draw into the canvas
the given image.
Exporting the content
var canvas = document.getElementById("mycanvas"); //you can change this to your image
var img = canvas.toDataURL("image/png");
Saving the image
Once you have successfully created the img
variable, you can save it. You can store it into localStorage
, like
localStorage.setItem('saved', img)
You can store it differently as well, like sending the image to your server in a POST request, but, for the purpose of this question I aim to have a simple solution that works. It would be another task to store this as a file or something of the like in your server.
Loading the image
let img = document.createElement('img');
img.src = localStorage.getItem('saved');
It is possible that img
was not saved yet, like in the first load. You will need to properly handle that case, like
if (img.src) {
//do some stuff
}
Putting an image into a canvas
canvas.getContext('2d').drawImage(img, dx, dy);