Canvas5性能问题绘制多行

时间:2021-04-07 16:53:54

I am currently creating a game using canvas and javascript and am having performance issues when I attempt to draw many lines.

我目前正在使用canvas和javascript创建一个游戏,并且当我尝试绘制多行时遇到性能问题。

The user is able to "fire" missiles to the coordinates where the mouse is clicked in an attempt to destroy oncoming meteors, and I want canvas to draw the line progressively from the "turret" to where the user clicked.

用户能够“点击”导弹到点击鼠标的坐标,试图摧毁迎面而来的流星,我希望画布从“炮塔”逐渐绘制线到用户点击的位置。

This is the function that listens for the click and draws the line to where the user clicks

这是侦听单击并将行绘制到用户单击位置的函数

canvas.addEventListener('click', function() {

// uses the function getMousePos to get coords
var mousePos = getMousePos(canvas, event);
var endX = mousePos.x;
var endY = mousePos.y;

var amount = 0;
var startX = w/2;
var startY = h; 

// draw the line from turret
setInterval(function() {
    amount += 0.005;
    if (amount > 1) amount = 1;
    ctx.strokeStyle = 'black';
    ctx.moveTo(startX, startY);

    ctx.lineTo(startX + (endX - startX) * amount,
            startY + (endY - startY) * amount);

    ctx.stroke();
}, 20);
})

https://jsfiddle.net/oohyefwa/

After I draw 10 or so lines canvas becomes incredibly laggy and for a game would be unacceptable.

在画了10个左右的画布后,画布变得非常迟钝,对于游戏来说是不可接受的。

Are there more efficient ways to do what I'm trying do to?

有没有更有效的方法来做我正在尝试做的事情?

1 个解决方案

#1


Add a beginPath() to your draw loop. If not the lines will accumulate and all will be redrawn over and over eventually lagging down the browser.

在绘制循环中添加一个beginPath()。如果不是这些线将累积,所有将重复重绘,最终落后于浏览器。

Example

setInterval(function() {
    ctx.beginPath();    // <----

    amount += 0.005;
    if (amount > 1) amount = 1;
    ctx.strokeStyle = 'black';
    ctx.moveTo(startX, startY);

    ctx.lineTo(startX + (endX - startX) * amount,
            startY + (endY - startY) * amount);

    ctx.stroke();
}, 20);
})

#1


Add a beginPath() to your draw loop. If not the lines will accumulate and all will be redrawn over and over eventually lagging down the browser.

在绘制循环中添加一个beginPath()。如果不是这些线将累积,所有将重复重绘,最终落后于浏览器。

Example

setInterval(function() {
    ctx.beginPath();    // <----

    amount += 0.005;
    if (amount > 1) amount = 1;
    ctx.strokeStyle = 'black';
    ctx.moveTo(startX, startY);

    ctx.lineTo(startX + (endX - startX) * amount,
            startY + (endY - startY) * amount);

    ctx.stroke();
}, 20);
})