【发布时间】:2018-03-09 21:03:25
【问题描述】:
我想在画布上围绕其中心旋转图像。
预期:图像在其中心旋转
当前结果:图像旋转一圈
代码包含:
- 创建精灵并返回它的精灵类。
- 用于更新精灵位置的动画循环。
我尝试调整绘制图像方法参数,但旋转未居中。它似乎在它的角落里旋转。怎么了?
var c = document.getElementById("myCanvas");
function sprite(options) {
var that = {};
that.context = options.context;
that.width = options.width;
that.height = options.height;
that.image = options.image;
that.x = options.x;
that.y = options.y;
that.angle = 0;
that.render = function() {
that.context.clearRect(that.x, that.y, that.width, that.height);
that.context.save();
that.context.translate(that.x + that.width / 2, that.y + that.height / 2);
that.context.rotate(that.angle * Math.PI / 180);
//---------------------->?? this is not working properly here.
that.context.drawImage(
that.image,
0,
0,
);
that.context.restore();
};
return that;
}
var ship_img = new Image();
ship_img.src = 'https://chrismalnu.files.wordpress.com/2016/01/f-15-cipher-copy.png?w=640';
var ctx = c.getContext("2d");
var coin = sprite({
context: c.getContext("2d"),
width: 100,
height: 100,
image: ship_img,
x: 200,
y: 200,
});
var sp1 = new Image();
sp1.src = 'https://pbs.twimg.com/media/B59SYYlCUAAL6A0.png';
var ssp = sprite({
context: c.getContext("2d"),
width: 50,
height: 50,
image: sp1,
x:100,
y:100,
});
dt = 3
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37:
// alert('left');
coin.x -= dt;
break;
case 38:
// alert('up');
coin.y -= dt;
break;
case 39:
// alert('right');
// coin.x+=dt;
coin.rotate();
break;
case 40:
// alert('down');
coin.y += dt;
break;
}
};
function mainLoop() {
// coin.x+=1;
coin.angle += 1;
ssp.angle -=1;
coin.render();
ssp.render();
requestAnimationFrame(mainLoop);
}
// Start things off
requestAnimationFrame(mainLoop);
<canvas id="myCanvas" width="600" height="390" style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
【问题讨论】:
-
也许在翻译前尝试旋转
-
@DylanMissuwe 它现在仍然有效。如果你能展示一下,我有疑问
标签: javascript html html5-canvas