JS / HTML5 - Redraw canvas with image data from array

I am trying to implement a cancel function for a canvas. Basically, people can draw on canvas, and then restore it to the state it used to be. This is a theory. I save the current imageData every time I call the draw function. It is stored in the eD (namespace) .history array. Drawing works great even if I manipulate the image. Here's my draw-function (cD is also a namespace):

editorClass.prototype.draw = function(){ eD.history.push(cD.imageData); cD.context.putImageData(cD.imageData, 0, 0); } 

Now, if I try to undo my changes that I made between them, I use the undo function, which looks like this:

 editorClass.prototype.undo = function(){ var temp = eD.history.pop(); cD.context.createImageData(cD.width,cD.height); //Can leave this out, nothing changes cD.context.putImageData(temp, 0, 0); } 

As mentioned above, this will not work. The canvas that I work with is created after the user loads the site. cD.imageData is taken from this function:

 editorClass.prototype.getPixels = function(){ cD.imageData = cD.context.getImageData(0, 0, cD.width, cD.height); // get the image data of the context and save them into namespace cD.pixels = cD.imageData.data; // get the pixels cD.pixelsLength = cD.width * cD.height * 4; // precompute the length of the pixel array } 

Both namespaces are visible if necessary. Since I'm pretty new to canvas, this might be a simple question, so if you have any improvements: I'm empty bucked, fill me in;)

thanks

+4
source share
1 answer

Not seeing all the code, I'm not sure why yours is not working, but I suspect that it only tries to put putImageData using an array of pixels, not an image data object.

Here is what I wrote that works

Live demo

And here is the corresponding code

 var savedData = []; undoButt.addEventListener("click", function () { // as long as there is data put it onto the canvas. if (savedData.length > 0) { var imgData = savedData.pop(); drawCtx.putImageData(imgData, 0, 0); } }); drawCanvas.addEventListener("mousedown", function (e) { // push the current state var imgData = drawCtx.getImageData(0, 0, drawCanvas.width, drawCanvas.height); savedData.push(imgData); }); 

With the same concept that you used, it works fine.

+3
source

Source: https://habr.com/ru/post/1496050/


All Articles