Save canvas / image after applying css
I have a simple canvas with an image on it (image 500x333):
<canvas id="capEdit" width="500" height="333"></canvas> Then I apply just horizontal flip on canvas / image using CSS, works fine
.flipH { -moz-transform: scale(-1, 1); -webkit-transform: scale(-1, 1); -o-transform: scale(-1, 1); transform: scale(-1, 1); filter: FlipH; } Now I am trying to save the image on the canvas with its inverted state, but it only saves the original image, this is what I am trying:
$(document).on("click", "#applyFlip", function() { // save var canvas = document.getElementById("capEdit"); var dataUrl = canvas.toDataURL(); $.ajax({ type: "POST", url: '/ajax/saveFlip.php', dataType: 'text', data: { base64data : dataUrl, imgName : imgName } }); }); QUESTIONS: If it works? If so, why is this not so? If he CANNOT even work like that, is there a way to achieve these results? In principle, horizontal and vertical turning and turning and then saving
The problem here is that when using CSS, you actually do not transform the image, except visually. You must actually transform the canvas context of the image.
Here is a pretty good explanation: http://davidwalsh.name/convert-canvas-image
function convertImageToCanvas(image) { var canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; canvas.getContext("2d").drawImage(image, 0, 0); return canvas; } After you draw the image in Canvas using the getContext method, you can apply transforms, rotate, translate using canvas methods, not CSS. If you change it using CSS, you only edit its appearance in the browser, you do not actually manipulate pixel data. You will need to do something like this before drawing the image:
// translate context to center of canvas context.translate(canvas.width / 2, canvas.height / 2); // rotate 180 degrees clockwise context.rotate(Math.PI); This is a bit beyond the scope of this question to explain how the canvas works, but look at the Canvas api for how to transform your context. If you have an image in context, context conversion should be simple enough :)
As soon as you get the image of your canvas, as you need it, you need to get the data URI (new image) from it and pass that to your saveFlip.php function.
// Converts canvas to an image function convertCanvasToImage(canvas) { var image = new Image(); image.src = canvas.toDataURL("image/png"); return image; }