有没有办法停止乱写
正常( Chrome )图像:
乱写的图像(firefox):
我正在使用代码生成绘图路径
document.createElementNS(NS, "path");
这是 JsFiddle:JSFIDDLE
最佳答案
这里的问题似乎是 Chrome 和 Firefox 之间实现 offsetX
和 offsetY
的方式不同。
在 Firefox 中,当您越过红线时,返回的 offsetX
和 offsetY
值相对于红线的左上角 em>,不是 SVG。这就是为什么你的线条值跳到屏幕顶部并稍微离开了一点。
我不确定这是否是 Firefox 中的错误。
无论如何,您都不应该真正使用 offsetX
和 offsetY
来实现此目的。 “正确”的方法通常是获取 clientX
和 clientY
坐标并将它们转换为 SVG 坐标。
function screenToSVG(clientX, clientY)
{
// Create an SVGPoint for future math
var pt = svg.createSVGPoint();
pt.x = clientX;
pt.y = clientY;
// Apply the inverse of the CTM (SVG Current Transform Matrix) to get
// the equivalent point in SVG coordinate space
return pt.matrixTransform(svg.getScreenCTM().inverse());
}
这种方法的优点是,即使 SVG 不是以 1:1 比例绘制的,它也能工作。例如,如果它有一个 viewBox
。
(function() {
var stage = jQuery('#stage');
var isMouseDown = false;
var NS = "http://www.w3.org/2000/svg";
var penCount = 0;
stage.on('mousedown', mouseDown);
stage.on('mousemove', mouseMove);
stage.on('mouseup', mouseUp);
$('#stageClear').on('click',()=>{
$('.shape').remove()
})
function mouseDown(event) {
var pt = screenToSVG(event.clientX, event.clientY);
isMouseDown = true;
var shape = document.createElementNS(NS, "path");
shape.setAttribute("class", "shape");
shape.setAttribute("fill", "transparent");
shape.setAttribute("id", "pen" + penCount);
shape.setAttribute("stroke", "#2795ee");
shape.setAttribute("stroke-width", "4px");
shape.setAttribute("strokeLinecap", "round");
shape.setAttribute("d", "M " + pt.x + " " + pt.y + " ");
shape.setAttribute("pointer-events", "none");
stage.append(shape);
++penCount;
}
function mouseMove(event) {
var pt = screenToSVG(event.clientX, event.clientY);
if (isMouseDown) {
var depth = jQuery('#pen' + (penCount - 1)).attr("d");
jQuery('#pen' + (penCount - 1)).attr("d", depth + "L " + pt.x + " " + pt.y + " ");
}
}
function mouseUp(event) {
isMouseDown = false;
}
function screenToSVG(clientX, clientY)
{
// Create an SVGPoint for future math
var svg = stage[0];
var pt = svg.createSVGPoint();
pt.x = clientX;
pt.y = clientY;
// Apply the inverse of the CTM (SVG Current Transform Matrix) to get
// the equivalent point in SVG coordinate space
return pt.matrixTransform(svg.getScreenCTM().inverse());
}
})();
#stage{
width:100%;
height:610px;
border:1px solid;
}
#stageClear{
cursor:pointer;
}
#stagetext{
user-select:none;
-moz-user-select:none;
-ms-user-select:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg id="stage" >
<text id="stagetext" x="10" y="10px">draw on the stage using mouse</text>
<line x1="50" y1="300" x2="800" y2="300" style="stroke:rgb(255,0,0);stroke-width:2" />
</svg>
<button id="stageClear"> clear</button>
关于javascript - 在 mozilla firefox 上画线时,svg 路径会被乱写乱画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42945256/