画布高度太大时的性能问题

时间:2018-11-12 22:26:39

标签: jquery html5 performance canvas

我不知道我的问题是否可以解决,但我们走吧。

我有一个带有纯文本表的屏幕和一个覆盖该表的画布,以便用户使用平板电脑做笔记。
问题在于表格的大小已大大增加,这使得绘制功能非常慢。
有什么方法可以增加画布的高度而不损失性能吗?

这是我的代码:

$(window).on("load", function() {
    $("#canvas")
        .attr({
            height: $("#table").height(),
            width: $("#table").width()
        })
        .css({
            top: $("#table").offset().top
        })
        .on({
            draw: function() {
                var context = this.getContext("2d");

                context.beginPath();
                context.moveTo($(this).attr("lastX"), $(this).attr("lastY"));
                context.lineTo($(this).attr("currX"), $(this).attr("currY"));
                context.lineJoin = "round";
                context.lineWidth = $("#lineWidth").val();
                context.strokeStyle = $("#pickedColor").val();
                context.closePath();

                context.stroke();
            },
            erase: function() {
                var context = this.getContext("2d"),
                    radius = $("#lineWidth").val() * 2;

                context.save();
                context.beginPath();
                context.arc($(this).attr("currX"), $(this).attr("currY"), radius, 0, 2 * Math.PI, true);
                context.clip();
                context.clearRect($(this).attr("currX") - radius, $(this).attr("currY") - radius, radius * 2, radius * 2);
                context.restore();
            },
            "mousedown pointerdown": function(evt) {
                $(this).attr({
                    currX: evt.pageX - this.offsetLeft,
                    currY: evt.pageY - this.offsetTop,
                    lastX: evt.pageX - this.offsetLeft - 1,
                    lastY: evt.pageY - this.offsetTop - 1
                });

                if (!$("#pickedColor").val()) {
                    $(this).trigger("erase");
                } else {
                    $(this).trigger("draw");
                }

                $(this).data("active", true);
            },
            "mousemove pointermove": function(evt) {
                if ($(this).data("active")) {
                    $(this).attr({
                        currX: evt.pageX - this.offsetLeft,
                        currY: evt.pageY - this.offsetTop,
                        lastX: $(this).attr("currX"),
                        lastY: $(this).attr("currY")
                    });

                    if (!$("#pickedColor").val()) {
                        $(this).trigger("erase");
                    } else {
                        $(this).trigger("draw");
                    }
                }
            },
            "mouseup pointerup": function() {
                $(this).data("active", false);
            }
        });
});

从现在开始,谢谢大家的帮助。

0 个答案:

没有答案