Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw HTML5 Canvas lines given user input of X,Y points?

I am trying to build a floorplan model in Canvas. Currently I have a grid image in my canvas and have the ability for users to draw lines by clicking and dragging their mouse. But, this doesn't guarantee straight lines.

Is there anyway I can provide input fields in the html page for users to input the beginning and ending x and y coordinates of the lines, and have it updated in my canvas code? I'm a beginner when it comes to JS/AJAX, so any remedial help is appreciated :)

Right now, this is the section that dictates how the lines get drawn:

$(document).ready(function() {

    var canvas = document.getElementById('canvas');
    var context = canvas.getContext("2d");

    if(canvas.getContext) {
        $('#canvas').mousedown(function (evt) {
            var offset = $('#canvas').offset();
            context.beginPath();
            context.moveTo(20, 20);
        });

        $(document).mousemove(function(evt) {
            var offset = $('#canvas').offset();
            context.lineTo(evt.pageX - offset.left, evt.pageY - offset.top);
            context.stroke();
        }).mouseup(function() {
            $(document).unbind('mousemove');
            $(document).unbind('mouseup');
        });

        $('#clearcanvas').click(function () {
          context.clearRect(0, 0, 600, 580);    
        });
    }
}); 

I suspect it involves modifying following code:

context.lineTo(evt.pageX - offset.left, evt.pageY - offset.top);
like image 504
Cynthia Avatar asked Dec 05 '11 00:12

Cynthia


1 Answers

Very simply you could use 4 input fields and take the value of each when a button is pressed

button.addEventListener('click', function() {
    ctx.beginPath();
    ctx.moveTo(x1.value, y1.value);
    ctx.lineTo(x2.value, y2.value);
    ctx.stroke();
}, false);

http://jsfiddle.net/TeGGx/

like image 91
Simon Sarris Avatar answered Oct 03 '22 03:10

Simon Sarris