首先我要说的是我刚开始使用Canvas元素。我已经设法使用jQuery和html2canvas.js将div渲染为png,但我想将png逆时针旋转90度。
我假设我需要在画布阶段执行此操作,然后在将其输出为png之前将其作为持久即使在下载图像时 - 我将如何进行并完成该操作?
这就是我现在所做的,这是有效的(减去轮换)
html2canvas($("#portrait_back_div"), {
onrendered: function (canvas) {
//document.getElementById('canvas').appendChild(canvas);
var data = canvas.toDataURL('image/png');
var image = new Image();
image.src = data;
document.getElementById('portrait_back_png').appendChild(image);
//$( "#portrait_back_div" ).hide();
}
});
我感谢任何帮助,尽管这看起来像是一个基本问题。 This fiddle basically works on the same principles as my project it you want to take a look.
答案 0 :(得分:4)
您必须创建一个新画布,然后转换为居中以将原点移动到中心(此处用作旋转轴),旋转然后绘制图像。
最后从旋转的画布中提取图像。
html2canvas($("#portrait_back_div"), {
onrendered: function (canvas) {
// create intermediate canvas
var rotCanvas = document.createElement("canvas");
// swap width and height
rotCanvas.width = canvas.height;
rotCanvas.height = canvas.width;
// get context
var rctx = rotCanvas.getContext("2d");
// translate to center (rotation pivot)
rctx.translate(rotCanvas.width * 0.5, rotCanvas.height * 0.5);
// rotate -90° (CCW)
rctx.rotate(-Math.PI * 0.5);
// draw image offset so center of image is on top of pivot
rctx.drawImage(canvas, -canvas.width * 0.5, -canvas.height * 0.5);
// extract image from rotate canvas
var data = rotCanvas.toDataURL('image/png');
var image = new Image();
image.src = data;
document.getElementById('portrait_back_png').appendChild(image);
//$( "#portrait_back_div" ).hide();
}
});
// proof-of-concept example
var img = new Image;
img.onload = function() {
var rotCanvas = document.createElement("canvas");
var rctx = rotCanvas.getContext("2d");
rotCanvas.width = this.height;
rotCanvas.height = this.width;
rctx.translate(rotCanvas.width * 0.5, rotCanvas.height * 0.5);
rctx.rotate(-Math.PI * 0.5);
rctx.drawImage(this, -this.width * 0.5, -this.height * 0.5);
document.body.appendChild(this);
document.body.appendChild(rotCanvas)
};
img.src = "//i.imgur.com/YqeJUhl.jpg?1";

<h4>Original on top, rotated canvas at bottom</h4>
&#13;
答案 1 :(得分:-1)
在onrendered结束时添加:
image.style.transform = "rotate(90deg)";
您需要更多变换版本才能让它跨浏览器工作