我正在开发一个MVC 5应用程序,它绘制一个代表数据的圆圈的120个部分。
在初始绘图中,圆圈看起来很平滑:
但是,在重新绘制圆圈以显示更新的数据(使用javascript)后,圆圈看起来并不平滑。重绘圆圈有“残留”。
因此,如何在没有残留的情况下重绘画布圈?
.cshtml
@for (int i = 0; i < 120; i++)
{
var myCanvas = "myCanvas" + i;
<canvas id=@myCanvas width="355" height="355"></canvas>
}
的JavaScript
var start = 1.5; // top of circle
var end = start + 0.01667;
for (var j = 0; j < 120; j++) {
var myCanvas = "myCanvas" + j;
var canvas = document.getElementById(myCanvas);
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 152;
var startAngle = start * Math.PI;
var endAngle = end * Math.PI;
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, false);
context.lineWidth = 9;
// line color
if (/*there is data*/) {
context.strokeStyle = /*data color*/;
} else {
context.strokeStyle = "#ffffff";
}
context.stroke();
if (end >= 1.99) { // reset to draw the rest of the circle
start = 0;
end = 0 + 0.01667;
} else {
start += 0.01667;
end += 0.01667;
}
答案 0 :(得分:1)
在绘制下一种颜色之前,需要清除所有画布元素。
var clearCanvas = false;
function drawChunks() {
var start = 1.5; // top of circle
var end = start + 0.01667;
function rColor() {
var c = Math.floor(Math.random() * 0xFFFFFF).toString(16);
c = "#" + "000000".substr(c.length) + c;
return c;
}
for (var j = 0; j < 120; j++) {
var myCanvas = "myCanvas" + j;
var canvas = document.getElementById(myCanvas);
var context = canvas.getContext('2d');
if (clearCanvas == true) {
context.clearRect(0, 0, canvas.width, canvas.height);
}
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 152;
var startAngle = start * Math.PI;
var endAngle = end * Math.PI;
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, false);
context.lineWidth = 9;
// line color
if (Math.floor(Math.random() * 2) == 1) {
context.strokeStyle = rColor();
} else {
context.strokeStyle = "#ffffff";
}
context.stroke();
if (end >= 1.99) { // reset to draw the rest of the circle
start = 0;
end = 0 + 0.01667;
} else {
start += 0.01667;
end += 0.01667;
}
}
}
var rad = document.myForm.clear_canvas;
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
clearCanvas = this.value == 'yes' ? true : false;
};
}
drawChunks();
setInterval(drawChunks, 1000);
canvas {
position: absolute;
}
<form name="myForm">
Clear Canvas? yes
<input name="clear_canvas" type="radio" value="yes">| no
<input name="clear_canvas" type="radio" value="no" checked>
</form>
<hr/>
<script type="text/javascript">
(function() {
var html = "";
for (var i = 0; i < 120; i++) {
var myCanvas = "myCanvas" + i;
var canvas = '<canvas id=@myCanvas width="355" height="355"></canvas>';
html += canvas.replace(/\@myCanvas/, myCanvas);
}
document.write(html);
})();
</script>