按下空格键时,我正在尝试使用时钟指针的阴影轨迹跟随时钟指针。它重新绘制每个刻度:
var stage, cont, arrow, cursorWedge, spacebarState, cursorWedgeStart, fired;
var msg = document.getElementById('state-msg');
var KEYCODE_SPACEBAR = 32;
spacebarState = false; // for cursor shadow wedge
stage = new createjs.Stage("canvas");
cont = stage.addChild(new createjs.Container());
cont.x = stage.canvas.width / 2;
cont.y = 250;
cont.rotation -= 90;
var circle = new createjs.Shape();
circle.graphics.beginFill("DeepSkyBlue").drawCircle(0, 0, 150);
circle.x = 0;
circle.y = 0;
cont.addChild(circle);
cont.setChildIndex(circle, 0);
arrow = new createjs.Shape();
arrow.graphics.beginFill("black").drawRect(0, 0, 150, 2);
cont.addChild(arrow);
cursorWedge = new createjs.Shape();
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", tick);
document.body.addEventListener('keydown', function(e) {
msg.textContent = 'keydown:' + e.keyCode;
keyDown(e);
});
document.body.addEventListener('keyup', function(e) {
msg.textContent = 'keyup:' + e.keyCode;
keyUp(e);
});
function tick() {
arrow.rotation += 1;
if (spacebarState === true) {
cursorWedge.graphics.moveTo(0, 0);
cursorWedge.graphics.arc(0, 0, 150, cursorWedgeStart * Math.PI / 180, arrow.rotation * Math.PI / 180);
}
stage.update();
}
function keyDown(event) {
switch (event.keyCode) {
case KEYCODE_SPACEBAR:
if (!fired) { //avoiding repeated events
fired = true;
cursorWedge.graphics.f(createjs.Graphics.getRGB(0, 0, 0, 0.25));
spacebarState = true;
cursorWedgeStart = arrow.rotation;
cont.addChild(cursorWedge);
cont.setChildIndex(cursorWedge, cont.getNumChildren() - 1);
}
}
}
function keyUp(event) {
switch (event.keyCode) {
case KEYCODE_SPACEBAR:
fired = false;
spacebarState = false;
cursorWedge.graphics.clear();
cont.removeChild(cursorWedge);
}
}
<head>
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
</head>
<body>
Keyboard message: <span id="state-msg"></span>
<canvas id="canvas" width="500" height="400"> </canvas>
</body>
是否有任何方法可以重新绘制圆弧段而不会在按键长时间后显着减慢?
答案 0 :(得分:1)
在您的代码中,您将每个刻度添加到图形中。这意味着每个帧都绘制了前一帧的图形,并加上新帧的图形。这是附加的,因此在第100帧中,每个刻度等绘制100个弧。
如果您没有尝试创建附加效果,只需在重绘之前清除图形:
cursorWedge.clear()
.graphics.arc(0, 0, 150, cursorWedgeStart * Math.PI / 180, arrow.rotation * Math.PI / 180);
另一种方法是存储graphics command,并在刻度线上修改它。当阶段重绘时,它将使用图形更新值。
// In the init (at the top in your example)
var arcCommand = cursorWedge.graphics.moveTo(0,0)
.graphics.arc(0, 0, 150, Math.PI / 180, 0).command; // returns the last command
// In your tick
arcCommand.endAngle = arrow.rotation * Math.PI / 180;
如果你想要一个附加效果(我不相信你是这种情况)加上图形,每个刻度仍然非常昂贵。您可以缓存形状所在的容器,然后只需添加 new 图形命令,并更新缓存。查看Cache Update演示,也可以在GitHub中找到。