[英]JavaScript: HTML5 and sliding a ball up the page
對於HTML5和臭名昭着的Canvas元素,我是一個新手 。 目前,我在我的網頁上繪制了一個藍色的球,點擊了畫布元素后,球滑到一個位置(Y),我將其傳遞給drawCircle函數。 我想將球滑到 Y位置,而球則跳到Y位置。
這是我到目前為止的代碼:
var context, canvas;
var x = 100;
var y = 200;
var dx = 5;
var dy = .02;
function drawCircle(move) {
if(move) {
x = move.x
y = move.y
}
canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d')
context.clearRect(0,0,canvas.width, canvas.height);
context.beginPath()
context.fillStyle = "#0000ff";
context.arc(x, y, 20, 0, Math.PI*2, true);
context.closePath();
context.fill();
// if(x < 0 || x > canvas.width) dx=-dx;
// if(y < 0 || y > canvas.height) dy =- dy;
if(move) {
y+=dy
}
// x+=dx
// y+=dy
}
window.onload = function(e){
// setInterval(drawCircle, 10)
drawCircle()
canvas.onclick = function(){
var move = {
x: 100,
y: 100
}
drawCircle(move)
}
}
JSFiddle: http : //jsfiddle.net/Uam8z/1/
您可以像建議的代碼一樣使用setInterval
函數,這就是我做的方式..
var context, canvas;
var x = 100;
var y = 200;
var dx = 5;
var dy = 5; //0.02 makes it move v. slowly!
function drawCircle(move) {
if(move) {
x = move.x
y = move.y
}
context.clearRect(0,0,canvas.width, canvas.height);
context.beginPath()
context.fillStyle = "#0000ff";
context.arc(x, y, 20, 0, Math.PI*2, true);
context.closePath();
context.fill();
}
window.onload = function(e){
canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
drawCircle()
var interval;
canvas.onclick = function(){
if(interval) //don't run if already doing so..
return;
var end_move = {
x: 100,
y: 100
};
var interval = setInterval(function(){
if(x === end_move.x && y === end_move.y){
//stop animation case..
clearInterval(interval);
interval = undefined;
} else {
var newX;
if(Math.abs(x - end_move.x) < dx){
newX = x;
} else {
newX = (x > end_move.x) ? x-dx : x+dx;
}
var newY;
if(Math.abs(y - end_move.y) < dy){
newY = y;
} else {
newY = (y > end_move.y) ? y-dy : y+dy;
}
drawCircle({
x: newX,
y: newY
});
}
}, 10);
}
}
代碼設置了一個end_position
,其中球應該結束。 然后它設置一個間隔以在每次迭代時將其移動相同的距離,當它接近所需位置時,它通過將位置設置為所需位置來確保間隔終止。
您不需要繼續定義畫布並設置上下文。 這會處理向上滑動:
var context, canvas, target;
var x = 100;
var y = 200;
var dx = 5;
var dy = 2; //.2 is pretty slow
function drawCircle() {
// sliding up
if (y > target) {
y -= dy;
}
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath()
context.fillStyle = "#0000ff";
context.arc(x, y, 20, 0, Math.PI * 2, true);
context.fill();
context.closePath();
}
window.onload = function () {
// get canvas, and context once
canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
// set target y position
canvas.onclick = function (e) {
target = e.clientY;
}
// 30fps
setInterval(drawCircle, (1000 / 30));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.