Ask coding questions

← Back to all posts
How to get an ellipse on a JavaScript canvas to change its x coordinate
dnilem26 (0)

Hello,
I'm trying to make a animation where a object moving, but I can't find a way to make the object look like it is moving
The object I want to is labeled //object in the code
If anyone could help me it would be very helpful

Answered by idrgplayer (128) [earned 5 cycles]
View Answer
Comments
hotnewtop
idrgplayer (128)

im not sure
i have used
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
and then make a new ctx with the updates coordinates. Im a little confused on what you want to do.

realTronsi (914)

use use ctx.ellipse()

ctx.ellipse(x, y, radius1, radius2, direction, startAngle, endAngle);

very similar to ctx.arc() except with two radii and a rotation

dnilem26 (0)

@realTronsi I think you misunderstood me, I was asking how to make a ellipse move around on the canvas

realTronsi (914)

@dnilem26 simply change the x and y parameters

dnilem26 (0)

@realTronsi I tried that but when I do it doesn't work because I need to reprint it out each time. The problem with that is I don't get rid of the previous ellipse.

realTronsi (914)

@dnilem26 use ctx.clearRect(0, 0, width, height) to clear the screen

dnilem26 (0)

@realTronsi would that work for a ellipse?

realTronsi (914)

@dnilem26 clearRect clears the entire specified rectangle, which if you use 0, 0, canvas.width, canvas.height will clear the entire canvas. If you absolutely can't clear the entire canvas for whatever reason you can clear the ellipse itself by setting the stroke and/or fill to the background color and drawing it in the same position, though it's not recommended and it can't handle overlaps.