在飞镖中做这样的帆布运动的最佳方法是什么? http://jsfiddle.net/loktar/dMYvG/
我想要获得平滑的帆布运动,并希望看到Dart可以做什么。
Dart还有一个jsfiddle alt吗?
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = canvas.height = 300;
var x = 150,
y = 150,
velY = 0,
velX = 0,
speed = 2,
friction = 0.98,
keys = [];
function update() {
if (keys[38]) {
if (velY > -speed) {
velY--;
}
}
if (keys[40]) {
if (velY < speed) {
velY++;
}
}
if (keys[39]) {
if (velX < speed) {
velX++;
}
}
if (keys[37]) {
if (velX > -speed) {
velX--;
}
}
velY *= friction;
y += velY;
velX *= friction;
x += velX;
if (x >= 295) {
x = 295;
} else if (x <= 5) {
x = 5;
}
if (y > 295) {
y = 295;
} else if (y <= 5) {
y = 5;
}
ctx.clearRect(0, 0, 300, 300);
ctx.beginPath();
ctx.arc(x, y, 5, 0, Math.PI * 2);
ctx.fill();
setTimeout(update, 10);
}
update();
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
答案 0 :(得分:1)
我知道有TryDart!,但它看起来并不像JSFiddle那样强大。
至于你的例子,这是等效的Dart代码:
import 'dart:html';
import 'dart:math';
import 'dart:async';
void main() {
CanvasElement canvas = querySelector('canvas');
CanvasRenderingContext2D ctx = canvas.context2D;
canvas.width = canvas.height = 300;
int x = 150;
int y = 150;
double velY = 0.0;
double velX = 0.0;
int speed = 2;
double friction = 0.98;
Map<int, bool> keys = new Map<int, bool>();
void update() {
if (keys[38]) {
if (velY > -speed)
{
velY--;
}
}
if (keys[40]) {
if (velY < speed) {
velY++;
}
}
if (keys[39]) {
if (velX < speed) {
velX++;
}
}
if (keys[37]) {
if (velX > -speed) {
velX--;
}
}
velY *= friction;
y += velY;
velX *= friction;
x += velX;
if (x >= 295) {
x = 295;
} else if (x <= 5) {
x = 5;
}
if (y > 295) {
y = 295;
} else if (y <= 5) {
y = 5;
}
ctx.clearRect(0, 0, 300, 300);
ctx.beginPath();
ctx.arc(x, y, 5, 0, PI * 2);
ctx.fill();
var timer = new Timer(new Duration(milliseconds:10), update);
}
update();
document.body.onKeyDown.listen((e) => keys[e.keyCode] = true);
document.body.onKeyUp.listen((e) => keys[e.keyCode] = false);
}
您还可以利用Dart API中的内容(例如num.clamp)来简化代码。