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