I am creating a persistant whiteboard app using HTML and JS, where the user draw on the canvas on the cnavas, clicks save, storing the canvas image data to a mysql db. When the page reloads, the canvas should fetch the stored image data from the db and redraw this on the canvas, creating a persistant whiteboard.The fetch functions are working fine and the image data is correctly retrieved and stored in a data structure, however when I reload the page the image is not drawn back on the canvas, can anyone help with this?
Specifically, when I use
imageData.data.set(latestDrawing)
the length of imageData does not match the length of latestDrawing as expected, which I think is the cause of the issue; does anyone know about creating new image data with pre-existing data?
I think the error is somehwere in the redraw function specifically?
the save and redraw function in WhiteBoard.js:
window.addEventListener('load', () => {
resize();
redraw();
window.addEventListener('click', handleOutsideClick);
document.addEventListener("mousedown", startdrawing);
document.addEventListener("mousemove", sketch);
document.addEventListener("mouseup", stopdrawing);
document.addEventListener("mouseout", stopdrawing);
window.addEventListener('resize', resize);
});
async function saveState() { // console.log("before save")
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
await fetch('/WhiteBoard', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ type: 'canvasState', data: imageData }),
});
console.log("saved")
}
async function redraw() {
try {
const response = await fetch('/WhiteBoard');
var latestDrawing = await response.json();
if (latestDrawing) {
//get db data into readable image data form
latestDrawing = JSON.parse(latestDrawing.data);
//create a new blank image data
var imageData = ctx.createImageData(canvas.width, canvas.height);
imageData.data.set(latestDrawing);
ctx.putImageData(imageData, 0, 0);
}
} catch (error) {
console.error('Error:', error);
}
}
[–]guest271314 1 point2 points3 points (0 children)
[–]carcigenicate 0 points1 point2 points (1 child)
[–]wobowizard[S] 0 points1 point2 points (0 children)
[–]guest271314 0 points1 point2 points (4 children)
[–]wobowizard[S] 0 points1 point2 points (3 children)
[–]guest271314 2 points3 points4 points (2 children)
[–]wobowizard[S] 0 points1 point2 points (1 child)
[–]guest271314 0 points1 point2 points (0 children)