在保持图片高宽比的同时尝试旋转图像

时间:2018-12-18 08:52:23

标签: javascript html5-canvas

我的项目基本上要做的是从数据库中获取图片,将其放入画布中,移动它,放大和缩小,这是完美的工作。

下一步是旋转图片,我不知道我在做什么错。在图片中,我描述了访问画布时文档的外观。旋转图片后,它将移到画布之外。我的代码如下所示,我不知道我在做什么错。谢谢

enter image description here

function drawRotated(degrees) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.save();
        ctx.translate(image.width*0.15,image.height*0.15);
        ctx.rotate(degrees * Math.PI / 180);
        ctx.translate(-image.width*0.15,-image.height*0.15);
        ctx.drawImage(image, 0, 0, image.width*0.15, image.height*0.15);
}

2 个答案:

答案 0 :(得分:1)

也许这不是您期望的答案。我没有使用您的代码。希望对您有所帮助。

主要思想是以画布的原点为中心绘制图像。

window.onload = function() {
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
canvas.width = 200;
canvas.height = 200;

var gkhead = gk;
gkhead.src = gk.src;
let w =  gkhead.width; 
let h =  gkhead.height; 
let x = -w/2;
let y = -h/2;  
ctx.drawImage(gkhead,x,y,w,h);


function translateToThePoint(p){
ctx.save();
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.translate(p.x,p.y);
ctx.scale(.25,.25);
ctx.drawImage(gkhead,x,y,w,h);
ctx.restore();
}
  
function rotate(angleInRad, p){
ctx.save();
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.translate(p.x,p.y);
ctx.rotate(angleInRad);
ctx.scale(.25,.25);
ctx.drawImage(gkhead,x,y,w,h);
ctx.restore();
}



let p = {x:canvas.width/2,y:canvas.height/2} 
//translateToThePoint(p); 
rotate(-Math.PI/10,p);  

}
canvas {
  border:1px solid
}
<canvas id="canvas">
  <img id="gk" src='https://www.warrenphotographic.co.uk/photography/cats/38088.jpg' />
</canvas>

答案 1 :(得分:0)

我的问题的答案是:

function drawRotated(degrees) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.save(); //save canvas state
        ctx.rotate(90 * Math.PI / 180);
        ctx.translate(0,-image.height*0.15);
        ctx.drawImage(image, 30, 30, image.width*0.15, image.height*0.15);
}
相关问题