使用javascript html5在画布上绘制点(圆)

< canvas> 标签用于通过Javascript动态绘制图形。标签只是图形的容器, 必须使用脚本来实际绘制图形。在本文中, 你将学习如何根据用户单击的点在画布上绘制一个点。
首先, 在文档中创建所需大小的画布标签。

< !-- The canvas tag --> < canvas id="canvas" width="690" height="651"> < /canvas>

要在用户单击画布时在其上绘制点, 我们需要检索click事件并获取该单击的坐标。要获取相对于HTML5 Canvas的鼠标坐标, 我们可以创建一个getPosition()方法, 该方法返回鼠标坐标(x, y)基于客户端鼠标的位置和从窗口对象的getBoundingClientRect()方法获得的画布的位置。
// Event will be a click event which can be retrieved as first parameter in the addEventListener(function(event){}); or in jQuery with $("selector").click(function(event){}); function getPosition(event){var rect = canvas.getBoundingClientRect(); var x = event.clientX - rect.left; // x == the location of the click in the document - the location (relative to the left) of the canvas in the documentvar y = event.clientY - rect.top; // y == the location of the click in the document - the location (relative to the top) of the canvas in the document// This method will handle the coordinates and will draw them in the canvas.drawCoordinates(x, y); }

现在, 我们的drawCoordinates方法将根据单击在画布中的位置绘制点。它将画布的x(水平)坐标作为第一个参数, 并将画布的y(垂直)坐标作为第二个参数。
function drawCoordinates(x, y){var pointSize = 3; // Change according to the size of the point.var ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "#ff2626"; // Red colorctx.beginPath(); //Start pathctx.arc(x, y, pointSize, 0, Math.PI * 2, true); // Draw a point using the arc function of the canvas with a point structure.ctx.fill(); // Close the path and fill.}

以下信息显示了上述所有方法的一个已经有效的示例。转到结果选项卡, 看看它是如何工作的, 在母鸡上画很多点!
【使用javascript html5在画布上绘制点(圆)】该代码对所有分辨率都很友好, 因为它保持最简单。即使你放大文档, 也会正确绘制坐标。玩得开心 !

    推荐阅读