To make a car in Javascript, we can use the power of HTML5 canvas. Below is a sample code snippet that will draw a basic car on the canvas.
847 chars42 lines
In this example, we first create our canvas element through HTML and give it the ID "myCanvas". We then access this canvas object through Javascript by calling document.getElementById("myCanvas")
.
Next, we set the 2D rendering context for the canvas object by calling var ctx = canvas.getContext("2d")
.
From there, we can use the various drawing methods in the ctx
object to create our car.
We first draw the car body by calling ctx.fillRect(100, 75, 300, 50)
, which will create a red rectangle at (100, 75) on the canvas with width 300 and height 50. We then draw the wheels by calling ctx.arc(150, 125, 25, 0, 2 * Math.PI)
and ctx.arc(350, 125, 25, 0, 2 * Math.PI)
, which draws two black circles with radius 25 at (150, 125) and (350, 125) on the canvas.
To draw the windows, we simply draw a white rectangle using ctx.fillRect(225, 80, 50, 30)
. Finally, we write "CAR" in the middle of the car using ctx.fillText()
.
gistlibby LogSnag