我正在开发一个模拟洗牌的网页游戏,我想用一张画布来表示一张牌。我想知道是否有办法使用jquery或其他库旋转元素,使元素不再是X-Y对齐的。我知道我可以旋转画布坐标系,但我需要使画布比卡片大,才能渲染旋转的卡片。有没有办法直接旋转元素?非常感谢!
发布于 2013-12-06 04:08:12
在您将卡片绘制到html canvas之后,您的卡片只是一幅画。
你不能重新定位它,因为它只是画布上的像素。
您要做的是:
你可以使用html5的requestAnimationFrame (RAF)来做等待。RAF将在大约16毫秒后执行函数。它就像一个循环,你可以把你的代码放进去,它通常看起来像这样:
function animate(){
requestAnimationFrame(animate); // this will re-execute animate() in about 16ms
// draw a current animation on the canvas
}
要有效地旋转卡片,请执行以下操作:
将canvas context (context.save)
它看起来像这样:
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(100,100);
ctx.rotate(rotation);
ctx.drawImage(img,-img.width/2,-img.height/2);
ctx.restore();
下面是示例代码和一个小提琴:http://jsfiddle.net/m1erickson/X9Wam/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var rotation=0;
var img=new Image();
img.onload=function(){
animate();
}
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/card.png";
function animate() {
requestAnimationFrame(animate);
// Drawing code goes here
rotation+=Math.PI/120;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(100,100);
ctx.rotate(rotation);
ctx.drawImage(img,-img.width/2,-img.height/2);
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=350 height=350></canvas>
</body>
</html>
https://stackoverflow.com/questions/20408681
复制相似问题