我尝试旋转图像并使用按钮点击将其放入画布中。
我最初可以将图像调整到画布大小,但是当我旋转图像时,它将恢复到原始大小,并且在画布中只能看到图像的一部分。即使在旋转时,如何将图像适合画布。
我在markE上看过一个关于SO的例子,但是当图像尺寸较大时,画布会缩放到图像的大小。我需要画布大小恒定,并且图像大小在旋转和加载时相应地缩放。我尝试通过markE
尝试两个不同的答案来修改代码,但无法实现。
这是我的JSFiddle
答案 0 :(得分:1)
更新了JS小提琴链接 -
https://jsfiddle.net/oLyou41j/3/
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var currentDegrees=0;
var image=document.createElement("img");
image.src="http://b.static.trunity.net/files/299501_299600/299598/vertical-farming-chris-jacobs.jpg";
image.onload=function(){
//Remove extra lines
ctx.drawImage(image,0,0,canvas.height, canvas.width);
}
$("#clockwise").click(function(){
currentDegrees+=90;
drawRotated(currentDegrees);
});
$("#counterclockwise").click(function(){
currentDegrees-=90;
drawRotated(currentDegrees);
});
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);
//Changed Method
ctx.drawImage(image,-canvas.width/2,-canvas.height/2, canvas.height, canvas.width);
ctx.restore();
}
答案 1 :(得分:1)
JS小提琴链接,如果你想要方面适合。
https://jsfiddle.net/oLyou41j/4/
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var currentDegrees=0;
var image=document.createElement("img");
image.onload=function(){
var wrh = image.width / image.height;
var newWidth = canvas.width;
var newHeight = newWidth / wrh;
if (newHeight > canvas.height) {
newHeight = canvas.height;
newWidth = newHeight * wrh;
}
ctx.drawImage(image,0,0,newWidth,newHeight);
}
image.src="http://b.static.trunity.net/files/299501_299600/299598/vertical-farming-chris-jacobs.jpg";
$("#clockwise").click(function(){
currentDegrees+=90;
drawRotated(currentDegrees);
});
$("#counterclockwise").click(function(){
currentDegrees-=90;
drawRotated(currentDegrees);
});
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);
var wrh = image.width / image.height;
var newWidth = canvas.width;
var newHeight = newWidth / wrh;
if (newHeight > canvas.height) {
newHeight = canvas.height;
newWidth = newHeight * wrh;
}
ctx.drawImage(image,-canvas.width/2,-canvas.height/2,newWidth,newHeight);
ctx.restore();
}