简体   繁体   English

在JavaScript中的画布上使用鼠标事件绘制直线

[英]Drawing a straight line using mouse events on canvas in javascript

I am trying to draw a straight line on canvas using mouse events.I am new to java script. 我正在尝试使用鼠标事件在画布上绘制一条直线。我是Java脚本的新手。 Can anybody help or refer something from where i can get help? 有人可以帮助我吗?

 <!doctype html> <html> <head> <meta charset="utf-8"> <style> body { background-color: black; } canvas { position: absolute; margin: auto; left: 0; right: 0; border: solid 1px white; border-radius: 10px; } </style> </head> <body> <canvas id="canvas"></canvas> <script type="application/javascript"> var canvasWidth = 180; var canvasHeight = 160; var canvas = null; var bounds = null; var ctx = null; var hasLoaded = false; var startX = 0; var startY = 0; var mouseX = 0; var mouseY = 0; var isDrawing = false; var existingLines = []; function draw() { ctx.fillStyle = "#333333"; ctx.fillRect(0,0,canvasWidth,canvasHeight); ctx.strokeStyle = "black"; ctx.lineWidth = 2; ctx.beginPath(); for (var i = 0; i < existingLines.length; ++i) { var line = existingLines[i]; ctx.moveTo(line.startX,line.startY); ctx.lineTo(line.endX,line.endY); } ctx.stroke(); if (isDrawing) { ctx.strokeStyle = "darkred"; ctx.lineWidth = 3; ctx.beginPath(); ctx.moveTo(startX,startY); ctx.lineTo(mouseX,mouseY); ctx.stroke(); } } function onmousedown(e) { if (hasLoaded && e.button === 0) { if (!isDrawing) { startX = e.clientX - bounds.left; startY = e.clientY - bounds.top; isDrawing = true; } draw(); } } function onmouseup(e) { if (hasLoaded && e.button === 0) { if (isDrawing) { existingLines.push({ startX: startX, startY: startY, endX: mouseX, endY: mouseY }); isDrawing = false; } draw(); } } function onmousemove(e) { if (hasLoaded) { mouseX = e.clientX - bounds.left; mouseY = e.clientY - bounds.top; if (isDrawing) { draw(); } } } window.onload = function() { canvas = document.getElementById("canvas"); canvas.width = canvasWidth; canvas.height = canvasHeight; canvas.onmousedown = onmousedown; canvas.onmouseup = onmouseup; canvas.onmousemove = onmousemove; bounds = canvas.getBoundingClientRect(); ctx = canvas.getContext("2d"); hasLoaded = true; draw(); } </script> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM