This site requires JavaScript, please enable it in your browser!
Greenfoot back

Report as inappropriate.

nccb presents ...


Line Drawing

This shows how to decide which pixels to fill when drawing a line on the screen. The thin black line is the "true" line, and the scenario provides a zoomed-in view of the pixels (white and orange squares) that are filled or left empty during the line-drawing.

Left-click to set the start point of the line, and right-click to set the end point.

A full explanation of the algorithm is here:

9426 views / 1270 in the last 7 days

2 votes | 0 in the last 7 days

Tags: with-source

open in greenfoot
Your browser does not support the canvas tag.


You're right that you can calulcate the angle from the two points. But how would you draw the line from the angle and two points? There are ways to do it, but they tend to either be potentially imprecise (will miss pixels in some circumstances) or slow. If you think you know a way, try implementing it to see if it works.
Your lines seem to be unusually thick o.O Especially when the angle of the line is 45 degrees. There is an incredibly fast (integer arithmatic only!) line drawing algorithm called the Bresenham's line algorithm that might work better in this situation.
Thanks, Builderboy, the Bresenham's line algorithm looks good. Though I do not understand why we need to know how to draw a line in java, since makes this easy.


The answer to Builderboy2005 and MatheMagician is the same: I used Wu (which gives thick lines) rather than Bresenham because the same algorithm can be used to do things like shooting: and visibility calculation: the latter of which is used again in the raycasting 3D example: Bresenham is not very suitable for these other purposes because it would let the shot/visibility pass through walls -- not so good!
Very good point! I wonder if it would be cool to have a button you could press to switch between the two algorithms, that was you could see how they differ :D


@MatheMagician It's always good to know how to do something, even if the graphics package already has classes which can do it :)


@nccb Maybe a late question, but why is Bresenhams algorithm not so good at 'lines of sight'?


Forget my last comment :)


@Builderboy2005 You're right: Bresenham has super fast algorithms (including one for a circle!). I've put them in my Fast graphics scenario, do you want to give some feedback?

See all comments

Want to leave a comment? You must first log in.

Who likes this?

nachocab dlanni