问题
I have a simple canvas with an image on it (image 500x333):
<canvas id="capEdit" width="500" height="333"></canvas>
I then apply a simply horizontal flip on the canvas/image using CSS, works perfectly
.flipH {
-moz-transform: scale(-1, 1);
-webkit-transform: scale(-1, 1);
-o-transform: scale(-1, 1);
transform: scale(-1, 1);
filter:
FlipH;
}
I'm now trying to save the image on the canvas WITH its flipped state, but it only saves the original image, here's what I'm 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: Should this work? If so, why does this not? If it CAN'T even work like this, is there a way to achieve these results? Basically, horizontal & vertical flipping and rotating, then saving
回答1:
The issue here is that when you use CSS, you're not actually transforming the image except visually. You need to actually transform the canvas context of the image.
Here's 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;
}
Once you have the image drawn in Canvas using the getContext
method, you can then apply transforms, rotates, translates, whatever using the canvas methods, not CSS. If you change it with CSS, you're only editing its appearance in the browser, you're not actually manipulating pixel data. You'd need to do something like this before actually 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);
It's a bit out of the scope of this question to explain how canvas works but look at the Canvas api for how exactly to transform your context. Once you have the image in the context, transforming the context should be easy enough :)
Once you get your canvas image to appear how you want it, you'll need to get a data URI from it (the new image) 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;
}
回答2:
I think it is normal that it doesn't work, the image you see is a rendered version, it doesn't affect the original.
Check this, it might help you out:
http://www.nihilogic.dk/labs/canvas2image/
来源:https://stackoverflow.com/questions/17025596/save-canvas-image-after-css-applied