我正在处理以下代码。为什么我无法在创作时翻转画布?我知道我可以使用CSS来做到这一点,但是由于我想下载具有填充格式的Canvas,所以我认为我需要以翻转模式创建它。
var sampleImage = document.getElementById("ringoImage"),
canvas = convertImageToCanvas(sampleImage);
// Actions
document.getElementById("canvasHolder").appendChild(canvas);
document.getElementById("pngHolder").appendChild(convertCanvasToImage(canvas));
// Converts image to canvas; returns new canvas element
function convertImageToCanvas(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0).scale(-1, 1);
return canvas;
}
// Converts canvas to an image
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Original Image</h2>
<img src="http://img.dailymail.co.uk/i/pix/2007/07_03/naniflipAP2607_468x652.jpg" id="ringoImage" />
<h2>Canvas Image</h2>
<div id="canvasHolder"></div>
<h2>Canvas -> PNG Image</h2>
<div id="pngHolder"></div>
答案 0 :(得分:0)
要做的三件事:
1)加载图像后开始处理(sampleImage.onload)
2)在添加图像之前翻转画布
3)避免在源img标签上使用crossOrigin =“ anonymous”保存受污染的画布
var sampleImage = document.getElementById("ringoImage");
sampleImage.onload = function() {
var canvas = convertImageToCanvas(sampleImage);
// Actions
document.getElementById("canvasHolder").appendChild(canvas);
document.getElementById("pngHolder").appendChild(convertCanvasToImage(canvas));
};
// Converts image to canvas; returns new canvas element
function convertImageToCanvas(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.translate(canvas.width, 0);
context.scale(-1, 1);
context.drawImage(image, 0, 0);
return canvas;
}
// Converts canvas to an image
function convertCanvasToImage(canvas) {
var image = new Image();
image.crossOrigin = "anonymous";
image.src = canvas.toDataURL("image/png");
return image;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Original Image</h2>
<img crossOrigin="anonymous" src="https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2Fmdn_logo-only_color.svg?1535749917189%22;" id="ringoImage" />
<h2>Canvas Image</h2>
<div id="canvasHolder"></div>
<h2>Canvas -> PNG Image</h2>
<div id="pngHolder"></div>