問題: 當我旋轉添加的圖像時,圖像沒有按照我希望的那樣居中。我一直在畫布上方的白色區域上方顯示圖片。在畫布內旋轉圖像時出現了一些問題
嘗試使用16:9的比例圖像,旋轉後您會看到我的問題。這將被用於移動,所以圖片的寬度可能是最大640
Here is a fiddle 當前代碼:
HTML:
<div id="files">
<input type="file" id="imageLoader" name="imageLoader" />
</div>
<canvas id="imageCanvas"></canvas>
<canvas id="preview"></canvas>
<input type="button" id="saveButton" value="Save" />
<div id="rotate">
<button type="button" id="rotateLeft">Rotate -90°</button>
<button type="button" id="rotateRight">Rotate 90°</button>
</div>
JS:
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var image = "";
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext("2d");
var fileName = "";
var angleInDegrees = 0;
function handleImage(e) {
var reader = new FileReader();
reader.onload = function(event) {
var img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0,0);
fileName = img.name;
image = img;
};
img.src = event.target.result;
};
reader.readAsDataURL(e.target.files[0]);
}
function drawRotated(degrees) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(canvas.width/2, canvas.height/2);
ctx.rotate(degrees * Math.PI/180);
ctx.drawImage(image, -image.width/2, -image.width/2);
ctx.restore();
}
$("#rotateRight").click(function() {
angleInDegrees += 90;
drawRotated(angleInDegrees);
});
$("#rotateLeft").click(function() {
angleInDegrees -= 90;
drawRotated(angleInDegrees);
});
這是我的ne w小提琴:)如果我想要它是最大640寬度?
jsfiddle.net/dJ5BH這是我的新小提琴:)如果我想什麼它是最大640寬度? – sindrem
您可以使用ctx.scale縮小任何圖像以適合您希望的最大寬度(640px寬度)。這裏有一個例子小提琴:http://jsfiddle.net/m1erickson/pYqTg/ – markE
謝謝! :)你在哪裏找到這些小提琴?! – sindrem