HTML5 Canvas 每次笔划都会变慢并清晰 [英] HTML5 Canvas slows down with each stroke and clear

查看:22
本文介绍了HTML5 Canvas 每次笔划都会变慢并清晰的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩 HTML5 Canvas,我注意到一些我无法在网上找到解决方案的东西.这是我正在玩的简单代码

I've been playing around with the HTML5 Canvas and I've noticed something that I couldn't find a resolution for online. Here's the simple code I'm playing with

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
    <canvas id="canvas" style="border: 1px solid;" width="200" height="200"></canvas>
    <br />
    <button id="draw">draw</button>
    <button id="clear">clear</button>
</body>
</html>

<script type="text/javascript">
    (function () {
        var canvas = document.getElementById("canvas");
        var context = canvas.getContext("2d");
        $("#draw").bind("click", function () {
            for (var i = 0; i < 200; i++) {
                context.moveTo(0, i);
                context.lineTo(100, 100);
                context.stroke();
            }
        });
        $("#clear").bind("click", function () {
            context.clearRect(0, 0, 200, 200);
        });
    } ());
</script>

我每次按下 draw 时,完成的速度似乎呈指数级减慢.有谁知道为什么会这样?

Each time that I press draw, the speed at which it completes seems to slow down exponentially. Could anyone know why this is happening?

它通过 IE 减慢速度.Chrome 似乎在每次绘制点击时完成它的速度更快,但您仍然可以明显地注意到速度降低.

It slows down the most through IE. Chrome seems to complete it faster with each draw click, but you can still definitely notice a speed reduction.

推荐答案

元素跟踪当前路径(即一组点、线和曲线).canvas.moveTocanvas.lineTocanvas.stroke 都对当前路径进行操作.每次调用 canvas.moveTocanvas.lineTo 时,都会添加到当前路径.随着路径越来越复杂,绘图速度也越来越慢.

The <canvas> element keeps track of a current path (i.e., set of points, lines, and curves). canvas.moveTo, canvas.lineTo, and canvas.stroke all operate on the current path. Every time you call canvas.moveTo or canvas.lineTo you are adding to the current path. As the path gets more and more complex, drawing gets slower and slower.

您可以通过调用canvas.beginPath() 来清除路径.在绘制函数开始时执行此操作应该可以消除减速.

You can clear the path by calling canvas.beginPath(). Doing this at the start of your draw function should get rid of the slowdown.

这篇关于HTML5 Canvas 每次笔划都会变慢并清晰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆