I'm trying to implement a game where you have car moving along a line in HTML5 Canvas. Using a little bit of trigonometrie I managed to get the right x and y coordinates to add to the coordinates of my image each frame to get to the end of the "line". Now the problem is, the image I use for the car starts to stutter in the process of rendering. The problem has to be the values I'm adding. (first I thought the problem would be the render loop but when using the render loop from paul irish the same problem occurs) My question is, how can I use floats in context.drawImage(img,...) smoothly?
What I tried was rounding the values where the image should move to (e.g. context.drawImage(img, Math.round(car.x), Math.round(car.y))) but this doesn't work also.
simple code example to demonstrate the issue: (using a simpler loop, but like I said, the problem isn't the loop)
Here is the whole thing:
var canvas = document.getElementById("canvasID");
var context = canvas.getContext("2d");
var car = new Car(20,10);
var carImg = new Image();
carImg.src = "https://i.stack.imgur.com/L2XQW.png";
function Car(x,y)
{
this.x = x;
this.y = y;
}
Car.prototype.advancePosition = function(x,y)
{
this.x = lerp(car.x, car.x + x, 1);
this.y = lerp(car.y, car.y + y, 1);
}
function update()
{
car.advancePosition(0.91,0.4);
}
function lerp (start, end, amt){
return (1-amt)*start+amt*end
}
function render()
{
context.beginPath();
context.clearRect(0,0, canvas.width, canvas.height);
context.drawImage(carImg, car.x, car.y);
context.closePath();
}
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame|| window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 100);
};
})();
(function mainLoop(){
requestAnimFrame(mainLoop);
render();
update();
})();
#canvasID
{
z-index: 1;
background: #eee;
display: block;
vertical-align: middle;
margin: 0 auto;
z-index: 1;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
position: absolute;
-webkit-transform:translateZ(1);
}
<html>
<head>
<meta charset = "utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="style.css">
<title>test</title>
</head>
<body>
<div class = "canvas_wrapper">
<canvas id="canvasID" width="500" height="450">Canvas not supported, please update your browser</canvas>
</div>
<script src="main.js"></script>
</body>
</html>
I would be happy if someone could help me out
Thanks
edit: Tried the suggestions from the comments but nothing worked.