1
我有一个网页,可让用户通过相机上传图片并对其进行绘制。所以我用html canvas
来实现免费的绘图部分。问题在于某些图像上传方向错误,因此我必须为用户提供一个按钮,让他们使用画布旋转图像。在变换后的操作后重新调整HTML画布大小
但是,在图像旋转后,我不知道如何调整画布的大小,使其具有与旋转图像相同的宽度和高度。现在,我有一些“空白”,我在循环后用我的代码中的蓝色背景标记。请在下面运行我的代码,以更好地了解我在这里要说的内容。
所以我的问题是如何在旋转后重新调整画布宽度和高度的大小,以便它具有与旋转图像相同的宽度和高度?
<!DOCTYPE html>
<html>
<head>
\t <title>Portrait</title>
</head>
<body>
\t <canvas id="myCanvas"></canvas><br/>
\t <input type="file" onchange="fileUpload(this.files)" id="file-input" capture="camera"><br/><br/>
\t <button onclick="rotate()">Rotate</button>
\t <script>
\t \t var file, canvas, ctx, image, fileURL, rotation = 90;
function fileUpload(files) {
file = files[0]
fileURL = URL.createObjectURL(file)
canvas = document.getElementById('myCanvas')
canvas.style.backgroundColor = "blue"
ctx = canvas.getContext('2d')
image = new Image()
image.onload = function() {
canvas.width = 500
canvas.height = (500 * this.height)/this.width
ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
}
image.src = fileURL
}
function rotate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save(); //save canvas state
ctx.translate(canvas.width/2, canvas.height/2);
ctx.rotate(rotation * Math.PI/180);
ctx.translate(-canvas.width/2, -canvas.height/2);
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
rotation += 90;
ctx.restore(); //restore canvas state
}
\t </script>
</body>
</html>
圣洁的狗屎,谢谢! – notQ