简体   繁体   English

如何在html画布上获取笔位置?

[英]How to get pen position on html canvas?

I think an older version of canvas had a canvas.PenPos property that let you see where the current pen location is.我认为旧版画布有一个canvas.PenPos属性,可让您查看当前笔的位置。 I'm mostly going to use this for debugging purposes and to draw relatively (eg a line 50px long to the right of the current position).我主要将它用于调试目的并进行相对绘制(例如,当前位置右侧的一条 50px 长的线)。 Is there any way to do this currently?目前有没有办法做到这一点? If not, why did they remove it...?如果没有,他们为什么要删除它......?

The pen position I'm referring to is the virtual "pen" that a drawing context (that you would get for example by calling var ctx = canvas.getContext('2d') ) uses, rather than a physical pen or mouse.我所指的笔位置是绘图上下文(例如,您可以通过调用var ctx = canvas.getContext('2d') )使用的虚拟“笔”,而不是物理笔或鼠标。

I am not trying to draw with a mouse.我不是想用鼠标画画。 Again, this is not a physical pen I'm looking for, it's the virtual pen that is moved with ctx.moveTo(x,y)同样,这不是我要找的物理笔,而是使用ctx.moveTo(x,y)移动的虚拟笔

try this尝试这个

 window.onload =function(){ var pad = document.querySelector("#pad"); var pctx = pad.getContext('2d'); pad.addEventListener("mousemove",function(e) { position = getPosition(pad,e); pctx.clearRect(0, 0, pad.width, pad.height); pctx.fillText("x: "+position.x +", y:" + position.y, 10, 10); })} function getPosition(p,e) { var a = p.getBoundingClientRect(); return { x : e.clientX - a.left, y : e.clientY - a.top }; }
 #pad { border:thin solid black; }
 <canvas id="pad" height="200" width="200">

According to w3.org , there isn't a method that returns the pen position.根据w3.org ,没有返回笔位置的方法。

Because the .getContext("2d") method returns an object, you can store the pen position as properties and call them as needed:因为 .getContext("2d") 方法返回一个对象,您可以将笔位置存储为属性并根据需要调用它们:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.beginPath();

//Start position
ctx.x = 100;
ctx.y = 100;
ctx.moveTo(ctx.x, ctx.y);
ctx.x = ctx.x + 100;
ctx.y = ctx.y + 300;
ctx.lineTo(ctx.x, ctx.y);
ctx.stroke();

When creating an arc though, you would need to calculate the pen's new position afterward.但是,在创建圆弧时,您需要随后计算笔的新位置。

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

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