首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用jquery的HTML5旋转元素

使用jquery的HTML5旋转元素
EN

Stack Overflow用户
提问于 2013-12-06 03:19:13
回答 1查看 121关注 0票数 0

我正在开发一个模拟洗牌的网页游戏,我想用一张画布来表示一张牌。我想知道是否有办法使用jquery或其他库旋转元素,使元素不再是X-Y对齐的。我知道我可以旋转画布坐标系,但我需要使画布比卡片大,才能渲染旋转的卡片。有没有办法直接旋转元素?非常感谢!

EN

回答 1

Stack Overflow用户

发布于 2013-12-06 04:08:12

在您将卡片绘制到html canvas之后,您的卡片只是一幅画。

你不能重新定位它,因为它只是画布上的像素。

您要做的是:

  • draw your rotation
  • repeat,
  • wait a short time
  • clear the canvas
  • 用稍微新的代码重新绘制您的卡片重复,重复!
  • repeat,>F211

你可以使用html5的requestAnimationFrame (RAF)来做等待。RAF将在大约16毫秒后执行函数。它就像一个循环,你可以把你的代码放进去,它通常看起来像这样:

代码语言:javascript
运行
复制
function animate(){

    requestAnimationFrame(animate);  // this will re-execute animate() in about 16ms

    // draw a current animation on the canvas

}

要有效地旋转卡片,请执行以下操作:

将canvas context (context.save)

  • move的未旋转状态保存到卡片位置的中心,因为您已将卡片(context.drawImage)

  • restore
  • context转换为未旋转状态,所以canvas会围绕卡片的中心点旋转一点。

它看起来像这样:

代码语言:javascript
运行
复制
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/

代码语言:javascript
运行
复制
<!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>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20408681

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档