绘制圆圈并保留第一个上传的精灵

时间:2014-11-17 20:58:24

标签: javascript html5 canvas

首先,我将一辆汽车上传到画布并给它转动和动作属性。我试图画一个圆圈与汽车并排,但它不能正常工作。由于某种原因,圆圈是孤独的和闪烁的。我完全取消了超时,圆圈和汽车都消失了。调整超时速率不会消除闪烁。帮我把它们放在屏幕上,然后把它们放在一起吗? http://jsbin.com/zogeraduze/1/edit?html,js,output

1 个答案:

答案 0 :(得分:1)

我没有您的汽车影像,但似乎您将setInterval设置为30毫秒,并且每隔10毫秒调用一次超时(相当于一个setInterval),每次清除画布,从而产生闪烁。你应该只有一个重绘功能,应该清除画布,绘制汽车,然后绘制圆圈。

//Setting the canvas and context
var canvas = document.getElementById('gameCanvas');
var context = canvas.getContext('2d');
//Uploading car
var car = new Image();
car.src = "file:///H:/Desktop/Game/img/car.png";

//Setting properties of car
var x = 450;
var y = 730;
var speed = 10;
var angle = 990;
var mod = 0;

//Event listeners for keys
window.addEventListener("keydown", keypress_handler, false);
window.addEventListener("keyup", keyup_handler, false);

//Drawing the car turning and changing speed
function draw() {

    x += (speed * mod) * Math.cos(Math.PI / 180 * angle);
    y += (speed * mod) * Math.sin(Math.PI / 180 * angle);

    context.save();
    context.translate(x, y);
    context.rotate(Math.PI / 180 * angle);
    context.drawImage(car, -(car.width / 2), -(car.height / 2));
    context.restore();
}

//Setting the keys
function keyup_handler(event) {
    console.log('a');
    if (event.keyCode == 38 || event.keyCode == 40) {

        mod = 0;
    }
}

//Setting all of the keys
function keypress_handler(event) {
    console.log(event.keyCode);
    if (event.keyCode == 38) {
        mod = 1;
    }
    if (event.keyCode == 40) {
        mod = -1;
    }
    if (event.keyCode == 37) {
        angle -= 5;
    }
    if (event.keyCode == 39) {
        angle += 5;
    }
}


var context = $('#gameCanvas')[0].getContext('2d');
var width = $('#gameCanvas').width();
var height = $('#gameCanvas').height();

var circleX = width / 2;
var circleY = height / 2;
var circleVX = 1.0;
var circleVY = 0.0;
var circleR = 30;

function update() {
  context.clearRect(0, 0, width, height);


/*
  circleX = Math.random() * (width - 2 * circleR) + circleR;
  circleY = Math.random() * (height - 2 * circleR) + circleR;
*/
  draw();
  drawCircle(circleX, circleY, circleR);

  setTimeout(update, 10);
}

function canvasClick(event) {
  var clickX = event.pageX;
  var clickY = event.pageY;
  var edgeX = clickX - circleX;
  var edgeY = clickY - circleY;
  var r = Math.sqrt(edgeX * edgeX + edgeY * edgeY);
  if (r < circleR) {
    context.clearRect(0, 0, width, height);
  }
}

function drawCircle(x, y, r) {
  context.beginPath();
  context.arc(x, y, r, 0, 2 * Math.PI, false);

  context.fillStyle = 'red';
  context.fill();

  context.lineWidth = 3;
  context.strokeStyle = 'black';
  context.stroke();
}

$('#gameCanvas').click(canvasClick);
update();

此外,请查看https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame而不是使用超时