How can I replicate 'skid marks' using HTML5 Canvas?
I've been creating a little experiment in HTML5 Canvas of a car with some basic movement, here it is: (arrow keys to move the car)
http://jsfiddle.net/mpxML/27/
The think I've been trying to figure out is the best way to create skid marks. If you hold the up key and turn you can see it creates some marks, but if you do it again, they link together. Obviously the way I am doing it isn't ideal. It's pushing the co-ordinates to an array and then using lineTo to link up those co-ordina开发者_Python百科tes.
Problems: - The lines link up - Pushing cordinates to an array to remember skids may not be the best method - I've only got one line, so when I add another, the performance will suffer futher.
What would you advise?
Sneaky question: Instead of having a fixed background, what's the best way to make the scene 'pan'.
Thanks, Henry
Try this http://jsfiddle.net/mpxML/34/.
I added MIN_DIST_TO_DRAW_SKID
variable. If two points in skidMarks
are farther than that value, the canvas does not draw a line(just call a moveTo
method).
This is part of code which I made changes:
// here
var MIN_DIST_TO_DRAW_SKID = 30;
function drawStageObjects() {
if(car.drift > 30 || car.drift < -30) {
skidMarks.push(car.x, car.y);
} else {
}
context.beginPath()
context.moveTo(skidMarks[0],skidMarks[1]);
for(var i=0; i < skidMarks.length; i = i + 2) {
skidPoint = Math.abs(skidMarks[(skidMarks.length-4)]) - Math.abs(skidMarks[(skidMarks.length-2)]);
// here
var dist = Math.sqrt((skidMarks[i] - skidMarks[i - 2]) * (skidMarks[i] - skidMarks[i - 2])
+ (skidMarks[i + 1] - skidMarks[i - 1]) * (skidMarks[i] - skidMarks[i - 1]));
if(skidPoint > 20 || dist > MIN_DIST_TO_DRAW_SKID) {
context.moveTo(skidMarks[i], skidMarks[i + 1]);
} else {
context.lineTo(skidMarks[i],skidMarks[i + 1]);
}
$('#stats').html(skidPoint);
//$('#stats').html(skidMarks[(skidMarks.length-4)] + "," +skidMarks[(skidMarks.length-2)]);
}
//....
}
精彩评论