Canvas 旋转描绘倾斜椭圆的图像
Canvas rotate image which depicts an angled ellipse
我的 canvas 中有一张图片,我正试图以一种不寻常的方式旋转它。我的图像在旋转,但原点错误。
我想以椭圆显示为从其原点旋转而不是图像本身旋转的方式旋转图像。最终椭圆将在 canvas 中静止并简单地旋转。
这是我当前的代码:
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
var angle;
var toRads = Math.PI/180;
var start = new Date().getTime();
var rotation = 15;
function draw(){
var x = canvas.width/2 - img.width/2;
var y = canvas.height/2 - img.height/2;
var deltaTime = new Date().getTime() - start;
start = new Date().getTime();
angle = (angle || 0) + (deltaTime/1000 * rotation);
if(angle > 360){angle = 0;}
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(x,y);
ctx.rotate(angle * toRads);
ctx.drawImage(img,20,20);
ctx.restore();
setTimeout(draw,1);
}
我想知道这是否可以在 2D 中完成,还是只能通过 3D(例如 webGL 之类的东西)来实现?
我创建了一个 jsfiddle,其中包含我目前所获得的内容:
http://jsfiddle.net/hc0p5e06/
转换的顺序很重要。您缺少将圆的原点放在正确位置的翻译(假设您想要圆心)
var w = img.width; // get the image width and height
var h = img.height;
ctx.translate(x,y);
ctx.rotate(angle * toRads);
ctx.drawImage(img,0,0,w,h,-w/2,-h/2,w,h); // draw the image translated half
// its size up and left in the new
// coordinate space
我的 canvas 中有一张图片,我正试图以一种不寻常的方式旋转它。我的图像在旋转,但原点错误。
我想以椭圆显示为从其原点旋转而不是图像本身旋转的方式旋转图像。最终椭圆将在 canvas 中静止并简单地旋转。
这是我当前的代码:
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
var angle;
var toRads = Math.PI/180;
var start = new Date().getTime();
var rotation = 15;
function draw(){
var x = canvas.width/2 - img.width/2;
var y = canvas.height/2 - img.height/2;
var deltaTime = new Date().getTime() - start;
start = new Date().getTime();
angle = (angle || 0) + (deltaTime/1000 * rotation);
if(angle > 360){angle = 0;}
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(x,y);
ctx.rotate(angle * toRads);
ctx.drawImage(img,20,20);
ctx.restore();
setTimeout(draw,1);
}
我想知道这是否可以在 2D 中完成,还是只能通过 3D(例如 webGL 之类的东西)来实现?
我创建了一个 jsfiddle,其中包含我目前所获得的内容: http://jsfiddle.net/hc0p5e06/
转换的顺序很重要。您缺少将圆的原点放在正确位置的翻译(假设您想要圆心)
var w = img.width; // get the image width and height
var h = img.height;
ctx.translate(x,y);
ctx.rotate(angle * toRads);
ctx.drawImage(img,0,0,w,h,-w/2,-h/2,w,h); // draw the image translated half
// its size up and left in the new
// coordinate space