对于HTML5和臭名昭著的Canvas元素,我是个新手。当前,我在网页上绘制了一个蓝色的球,并单击canvas元素,该球向上滑动到传递给drawCircle函数的位置(Y)。我想将球向上滑动到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/

最佳答案

您无需继续定义画布并设置上下文。这可以向上滑动:

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));
}

关于javascript - JavaScript:HTML5并在页面上滑动,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8902250/

10-11 11:15