这是一个在画布上绘制线条的JavaScript代码。
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);
}
如何为此添加按钮,以便在按钮单击时执行代码?我怎样才能做到这一点?下面给出一个例子来澄清事物
<input type="BUTTON" value="Exit" onclick="execute the javascript file to draw line" >
答案 0 :(得分:0)
首先,您需要在html中包含js文件:
<script src='file.js'></script>
然后,您可以执行init()函数onclick:
<input type="BUTTON" value="Exit" onclick="init()" >
答案 1 :(得分:-1)
首先,我会使用“button”标签而不是“input”来获得更好的语义。 其次,给按钮一个“onclick”参数并将其设置为等于“init”函数。
<button name="draw-line" onclick="init()"