html 画圆点代码,使用javascript html5在画布上绘制点(圆)

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

首先, 在文档中创建所需大小的画布标签。

要在用户单击画布时在其上绘制点, 我们需要检索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 document

var 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 color

ctx.beginPath(); //Start path

ctx.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.

}

以下信息显示了上述所有方法的一个已经有效的示例。转到结果选项卡, 看看它是如何工作的, 在母鸡上画很多点!

该代码对所有分辨率都很友好, 因为它保持最简单。即使你放大文档, 也会正确绘制坐标。玩得开心 !

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值