我在一张图片中有几个精灵,我想将各个精灵画到画布上。我无法让它们旋转。
当我尝试旋转精灵时,它似乎永远不会围绕应该旋转的点旋转。
我正在使用以下功能。角度设置为加载时间。
Sprite.prototype.draw = function (ctx, x ,y) {
if (this.angle == 0) {
ctx.drawImage(this.img, this.x, this.y, this.width, this.height, x, y, this.width, this.height);
}
else {
ctx.save();
ctx.translate(x, y);
ctx.rotate(this.angle * this._TORADIANS);
ctx.drawImage(this.img, this.x, this.y, this.width, this.height, x, y, this.width, this.height);
ctx.restore();
}
}
我查看了几个教程,在这种情况下似乎没有任何工作。
答案 0 :(得分:6)
首先将上下文翻译为x, y
加上图像的一半尺寸,以便上下文原点位于图像所需位置的中心位置:
ctx.translate(x + this.width / 2, y + this.height / 2);
按所需的度数旋转上下文:
ctx.rotate(this.angle * Math.PI / 180);
绘制图像,偏移其尺寸的一半以考虑原点的位置:
ctx.drawImage(this.img, this.x, this.y, this.width, this.height,
-this.width / 2, -this.height / 2, this.width, this.height);
现在撤消旋转和翻译:
ctx.rotate(-this.angle * Math.PI / 180);
ctx.translate(-x - this.width / 2, -y - this.height / 2);
在您的情况下,您可以按如下方式更改Sprite.draw()
。
Sprite.prototype.draw = function (ctx, x, y) {
ctx.save();
ctx.translate(x + this.width / 2, y + this.height / 2);
ctx.rotate(this.angle * Math.PI / 180);
ctx.drawImage(this.img, this.x, this.y, this.width, this.height,
-this.width / 2, -this.height / 2, this.width, this.height);
ctx.restore();
};
以下代码段演示了这种方法。
window.onload = function () {
var width = 600,
height = 600,
canvas = document.getElementsByTagName('canvas')[0],
context = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
var image = new Image();
image.src = 'http://www.dialfredo.com/wp-content/uploads/2015/05/redapplepic.jpg';
function draw(x, y, degrees) {
context.translate(x + image.width / 2, y + image.height / 2);
context.rotate(degrees * Math.PI / 180);
context.drawImage(image, 0, 0, image.width, image.height,
-image.width / 2, -image.height / 2, image.width, image.height);
context.rotate(-degrees * Math.PI / 180);
context.translate(-x - image.width / 2, -y - image.height / 2);
}
image.onload = function () {
var degrees = 0;
function loop() {
degrees = (degrees + 1) % 360;
draw(0, 0, degrees);
window.requestAnimationFrame(loop);
};
window.requestAnimationFrame(loop);
};
};
canvas {
border: 2px solid #ccc;
}
<canvas></canvas>
答案 1 :(得分:2)
如果您在x,y周围旋转,那么您的代码应如下所示:
SELECT LCMS.StrainId,date(DateTime),FlaskNum,HarvestIndex,Species,NumLabeledCarbons,MDV
FROM LCMS
JOIN ( SELECT StrainId,max(date(DateTime)) AS MaxDate
FROM LCMS
WHERE StrainId IN ('U','S','UG','SG')
GROUP BY StrainId) AS MD
ON LCMS.StrainId=MD.StrainId AND date(LCMS.DateTime)=MD.MaxDate
WHERE HarvestIndex = ( SELECT min(HarvestIndex)
FROM LCMS)
ORDER BY LCMS.StrainId,date(DateTime),FlaskNum,HarvestIndex,Species,NumLabeledCarbons;