gpt4 book ai didi

javascript - 恢复问题

转载 作者:行者123 更新时间:2023-12-02 20:27:54 25 4
gpt4 key购买 nike

我尝试使用canvas标签来允许用户绘制形状,但是绘制新线会导致所有其他线消失。 Try It (copy+paste to the textarea and click the "Edit and Click Me >>" button) 。值得一提的是,这个问题在所有 5 个最流行的浏览器(包括 IE7、8 和 IE9beta)中都存在。

代码:

<!DOCTYPE html>
<html>
<head>
<!-- ... -->
<!-- (a script used to support canvas in IE7,8) --><!--[if lte IE 8]>
<script type="text/javascript" src="http://explorercanvas.googlecode.com/svn/trunk/excanvas.js"></script>
<![endif]-->
<script type="text/javascript">//<![CDATA[
var cnvs, cntxt;
window.onload = function () {
cnvs = document.getElementById("cnvs");
cntxt = cnvs.getContext("2d");
//...
};

var lastX, lastY;
function beginLine(x, y) {
cntxt.moveTo(x, y);
cntxt.save();
lastX = x;
lastY = y;
cnvs.setAttribute("onmousemove", "preview(event.clientX, event.clientY);");
cnvs.setAttribute("onmouseup", "closeLine(event.clientX, event.clientY);");
}

function closeLine(x, y) {
cntxt.lineTo(x, y);
cntxt.stroke();
cntxt.save();
cnvs.removeAttribute("onmousemove");
cnvs.removeAttribute("onmouseup");
}

function preview(x, y) {
cntxt.beginPath();
cntxt.clearRect(0, 0, cnvs.width, cnvs.height);
cntxt.restore();
cntxt.moveTo(lastX, lastY);
cntxt.lineTo(x, y);
cntxt.stroke();
}
//]]></script>
</head>
<body>
<!-- ... -->
<canvas id="cnvs" style="position:absolute;top:0;left:0;border:1px black solid;" onmousedown="beginLine(event.clientX, event.clientY);"></canvas>
<p style="margin-top:200px;">(click and drag the mouse to draw a line)</p>
</body>
</html>

这可能是保存/恢复错误,但我找不到它。

<小时/>

我尝试过 2 个不同的论坛:

但没有人知道问题出在哪里。

最佳答案

您误解了保存恢复方法的含义。它们保存 Canvas 状态而不是内容。这意味着,当您发出 canvas.save() 时,您将保存 fillStylestrikeStylelineWidthlineJoin

解决问题的最简单方法是在内存中保留另一个相同大小的 Canvas ,然后释放鼠标按钮后,clearRect 并使用drawImage 方法。或者,您可以将线条插入数组并每次重新绘制它们(这可能比在现有 Canvas 上绘制另一 Canvas 更快)。

此外,还有一个关于clearRect的提示。事实证明,这种方法非常慢。在您的情况下,您使用它的频率不够高,不会对性能产生重大影响,但为 Canvas 对象分配相同的宽度高度要快得多。

关于javascript - <canvas>恢复问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4566495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com