绘制新线之前清除画布

问题描述 投票:0回答:2

我有一个画布形式的图表,当用户在我的表单中输入数字时,我想绘制一条水平线。

每次用户输入新数字时,都会绘制一条新线,并且仍显示旧线。我一次只需要显示一行。我该怎么做?

var c = document.getElementById("chartCanvas");
var ctx = c.getContext("2d");
let userInput = document.getElementById("userInput");

function drawIndexLine(index) {
  ctx.moveTo(index, 0);
  ctx.lineTo(index, 150);
  ctx.stroke();
}

userInput.addEventListener('change', function() {
  let value = Number(this.value);
  drawIndexLine(value);
})
canvas {
  border: solid;
}
<p>enter number <input id="userInput" type="number"></p>
<canvas id="chartCanvas"></canvas>

javascript html5-canvas
2个回答
1
投票

清除画布的一种快速而简单的方法是更新其至少一个尺寸 - 甚至更新为相同的尺寸。请注意,对此有一些警告(例如它可能会重置描边和填充设置),但对于此处介绍的用例来说,它们不是问题。

这是一个工作示例:

var canvas = document.getElementById("chartCanvas");
var ctx = canvas.getContext("2d");
let userInput = document.getElementById("userInput");

function drawIndexLine(index) {
  ctx.canvas.width = ctx.canvas.width;
  ctx.moveTo(index, 0);
  ctx.lineTo(index, 150);
  ctx.stroke();
}

userInput.addEventListener('change', function() {
  let value = Number(this.value);
  drawIndexLine(value);
})
canvas {
  border: solid;
}
<p>enter number <input id="userInput" type="number"></p>
<canvas id="chartCanvas"></canvas>

此外,正如旁注,这些线是垂直的而不是水平的。


0
投票

不要使用其他答案中的

canvas.width
setter hack,这将重置画布上下文的所有属性,并重置其位图缓冲区,这不仅超级慢,而且内存效率超级低。

而是使用

ctx.clearRect()
清除画布缓冲区(不替换它),并使用
ctx.beginPath()
开始新路径:

var c = document.getElementById("chartCanvas");
var ctx = c.getContext("2d");
let userInput = document.getElementById("userInput");

function drawIndexLine(index) {
  ctx.clearRect(0, 0, c.width, c.height);
  ctx.beginPath();
  ctx.moveTo(index, 0);
  ctx.lineTo(index, 150);
  ctx.stroke();
}

userInput.addEventListener('input', function() {
  let value = Number(this.value);
  drawIndexLine(value);
})
canvas {
  border: solid;
}
<p>enter number <input id="userInput" type="number"></p>
<canvas id="chartCanvas"></canvas>

© www.soinside.com 2019 - 2024. All rights reserved.