1. 程式人生 > >Chart.js清空canvas畫布 clearRect()等canvas方法擦除失敗(附完整程式碼)

Chart.js清空canvas畫布 clearRect()等canvas方法擦除失敗(附完整程式碼)

一、直接移除DOM物件方式

1.原因

clearRect()等canvas方法清空失敗

2.方法

移除dom物件的方式

$('#canvas').remove();
$('#container').append('<canvas id="canvas"></canvas>');

二、完整程式碼

1.html

<div id="container">
    <canvas id="canvas"></canvas>
</div>

2.javascript

/**
 *擦除canvas畫布
 */
function clearCanvas(){
    $('#canvas'
).remove(); $('#container').append('<canvas id="canvas"></canvas>'); container=document.getElementById("canvas"); context=container.getContext("2d"); }

3.chart.js畫圖方法

function pieChart(){
    clearCanvas();
    window.myPie = new Chart(context, config);
}
var config = {
    type
: 'pie', data: { datasets: [{ data: [ 40, 30, 20, 10 ], backgroundColor: [ window.chartColors.red, window.chartColors.orange, window.chartColors.green, window
.chartColors.blue, ], label: 'Dataset 1' }], labels: [ "優秀", "良好", "中等", "偏差" ] }, options: { responsive: true, legend: { position: 'top', }, title: { display: true, text: '餅狀圖' }, animation: { animateScale: true, animateRotate: true } } };

三、效果

餅狀圖