Meta_Data Meta_Data - 2 days ago 6
Javascript Question

Executing Javascript File On Click

This is a javascript code to draw lines on canvas.

var canvas,
context,
dragging = false,
dragStartLocation,
snapshot;


function getCanvasCoordinates(event) {
var x = event.clientX - canvas.getBoundingClientRect().left,
y = event.clientY - canvas.getBoundingClientRect().top;

return {x: x, y: y};
}

function takeSnapshot() {
snapshot = context.getImageData(0, 0, canvas.width, canvas.height);
}

function restoreSnapshot() {
context.putImageData(snapshot, 0, 0);
}


function drawLine(position) {
context.beginPath();
context.moveTo(dragStartLocation.x, dragStartLocation.y);
context.lineTo(position.x, position.y);
context.stroke();
}

function dragStart(event) {
dragging = true;
dragStartLocation = getCanvasCoordinates(event);
takeSnapshot();
}

function drag(event) {
var position;
if (dragging === true) {
restoreSnapshot();
position = getCanvasCoordinates(event);
drawLine(position);
}
}

function dragStop(event) {
dragging = false;
restoreSnapshot();
var position = getCanvasCoordinates(event);
drawLine(position);
}

function init() {
canvas = document.getElementById("canvas");
context = canvas.getContext('2d');
context.strokeStyle = 'black';
context.lineWidth = 6;
context.lineCap = 'round';

canvas.addEventListener('mousedown', dragStart, false);
canvas.addEventListener('mousemove', drag, false);
canvas.addEventListener('mouseup', dragStop, false);
}


How can i add a button to this so that when the button clicked the code get executed? How can i do this? An example is given below to clarify the thing

<input type="BUTTON" value="Exit" onclick="execute the javascript file to draw line" >

Answer

First, I would use the "button" tag instead of "input" for better semantics. Second, give the button an "onclick" parameter and set it equal to your "init" function.

<button name="draw-line" onclick="init()"
Comments