html5-canvas - 如何删除 HTML5 canvas 中的特定 stroke?

我在 HTML5 canvas 中制作了几个 strokes。为了用 stroke 制作动画,我像这样清除以前的:

// Notice : canvasWidth, canvasHeight, context are in a parent scope
    function echoLine( posLeftX, posLeftY, posRightX, posRightY) {
        context.beginPath();
        context.moveTo(posLeftX, posLeftY);
        context.clearRect(0, 0, canvasWidth, canvasHeight);
        context.bezierCurveTo(posLeftX, posLeftY, posRightX, posLeftY, posRightX, posRightY);
        context.stroke();
        context.closePath();
    }

我的问题是当我想做几行动画时,context.clearRect() 将全部删除,而我没有找到其他方法来删除特定的 stroke。

有没有办法在没有解决方法的情况下清除特定的 stroke ,或者我应该通过 stroke 来创建上下文?

回答1

您可以保留一个线数组,每次都绘制它们,然后 delete 是数组上的一个简单 splice ,您只需稍微更改绘制函数以清除然后循环遍历我们进行所有绘图的数组.

这是一个例子。

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d")
var lines = []

function draw() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  lines.forEach((e, i) => {
    context.beginPath();
    context.moveTo(e.left.x, e.left.y);    
    context.fillText(i, e.left.x-7, e.left.y);
    context.bezierCurveTo(e.left.x, e.left.y, e.right.x, e.left.y, e.right.x, e.right.y);
    context.stroke();
  })
}

function animate() {
  lines.forEach((e) => { 
    if (e.right.y > 150 || e.right.y < 0) e.speed *= -1 
    e.right.y += e.speed      
  })
  draw()
}

document.getElementById('todelete').onkeyup = (event) => {
  if (event.keyCode == 13) {
    lines.splice(event.srcElement.value, 1)
    event.srcElement.value = ""
  }
};

for (var i = 2; i < 8; i++) {
  lines.push({ 
    left:  { x:10,   y:130 - i*16 }, 
    right: { x:i*30, y:50 - i*6 }, 
    speed: 0.2 + Math.random() 
  })
}

setInterval(animate, 40)
input {
  width: 160px
}
<input id="todelete" type="number"  min="0" max="5" placeholder="enter number to delete" >
Press enter to submit.
<br>
<canvas id="canvas" width=300 height=150></canvas>

相似文章

html - 将按钮移动到标题的右侧

我正在尝试将这两个按钮移到标题的右侧,但我不知道为什么不能。我真的尝试了一切。我尝试创建一个div来插入两个按钮,尝试向这些按钮添加一个特定的类,并将它们对齐到右侧,但这些都不起作用。header{d...

随机推荐

最新文章