Question: Using HTML5 and JavaScript Extend Bresenham's line-drawing algorithm to work for all slopes using symmetry. The user left clicks to select the start of a
Using HTML5 and JavaScript
Extend Bresenham's line-drawing algorithm to work for all slopes using symmetry. The user left clicks to select the start of a line segment and releases the button to select the endpoint. Your code should continuously display the line while the left button is held down.
Here is the code to extend:
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.addEventListener("mousedown", handleMouseDown);
canvas.addEventListener("mousemove", handleMouseMove);
canvas.addEventListener("mouseup", handleMouseUp);
var p0 = {x: 0, y:0};
var p1 = {x: 0, y:0};
var isdown = 0;
display();
function handleMouseUp(event)
{
isdown = 0;
p1.x = event.clientX - canvas.offsetLeft;
p1.y = event.clientY - canvas.offsetTop;
display();
}
function handleMouseDown(event)
{
isdown = 1;
p0.x = event.clientX - canvas.offsetLeft;
p0.y = event.clientY - canvas.offsetTop;
display();
}
function handleMouseMove(event)
{
if (isdown == 0)
return;
p1.x = event.clientX - canvas.offsetLeft;
p1.y = event.clientY - canvas.offsetTop;
display();
}
function midpoint(p0, p1)
{
var dy = p1.y - p0.y;
var dx = p1.x - p0.x;
var incE = -2*dy;
var incNE = 2*dx + incE;
var d = dx - 2*dy;
var x, y;
y = p0.y;
for (x = p0.x; x <= p1.x; ++x)
{
context.fillRect(x, y, 1, 1);
if (d >= 0)
d += incE;
else
{
d += incNE;
++y;
}
}
}
function display()
{
context.clearRect(0, 0, canvas.width, canvas.height);
var dx = p1.x - p0.x;
var dy = p1.y - p0.y;
if (dx > 0 && dy > 0 && dx >= dy)
midpoint(p0, p1);
context.fillStyle = "#00FF00";
context.strokeStyle = "#FF0000";
// context.beginPath();
// context.moveTo(p0.x, p0.y);
// context.lineTo(p1.x, p1.y);
// context.stroke();
}
