Javascript 从画布形状清除文本

Javascript 从画布形状清除文本,javascript,canvas,html5-canvas,Javascript,Canvas,Html5 Canvas,如何从画布形状清理文本? 这是我的代码: <div id="ways" style="width:1000px;margin:0 auto;height:100%;"> <canvas id="canvas" width="1000" height="1000"></canvas> 而且只要稍微重构一下代码就可以了- 将绘制圆的线条提取到单个函数中,该函数将这些圆对象之一作为参数: function drawCircle(circle) { c

如何从画布形状清理文本? 这是我的代码:

<div id="ways" style="width:1000px;margin:0 auto;height:100%;">
<canvas id="canvas" width="1000" height="1000"></canvas>


而且只要稍微重构一下代码就可以了-

将绘制圆的线条提取到单个函数中,该函数将这些圆对象之一作为参数:

function drawCircle(circle) {
    context.beginPath();
    context.arc(circle.x, circle.y, circle.radius, 0, 2 * Math.PI, false);
    context.fillStyle = 'green';
    context.fill();
    context.lineWidth = lineWidth;
    context.strokeStyle = '#003300';
    context.stroke();
}
然后用这条线替换循环中它们最初来自的线(在推送圆对象之后):

现在,您可以通过修改代码在单击事件中使用此功能(在这里,它可以打开和关闭文本):


这种方法只需注意一点:这将重新绘制相互重叠的圆。随着时间的推移,由于边缘上添加了抗锯齿,线条将开始看起来锯齿状。出于这个原因,最好完全清除画布,然后重新绘制它们。但我会把它留给你做练习…-)

当点击一个圆圈乘以时间时,圆圈的边缘就变了,而且很难看@Ghost要重绘全部,请使用clearRect(0,0,宽度,高度),然后再次重绘所有圆和线(或将它们绘制到屏幕外画布,并将其用作主画布的图像源,然后使用drawImage()),如何在重绘时为特殊圆设置单击属性?
drawCircle(circles[circles.length-1]);   // draw last added circle
if (context.isPointInPath(x, y)) {
    if (circle.clicked) {
        drawCircle(circle);        // now we can reuse this function to clear the text
        circle.clicked = false;
    }
    else {
        circle.clicked = true;
        context.fillStyle = "blue";
        context.font = "bold 34px Arial";
        context.textAlign="center";
        context.fillText("Yeah", circle.x, circle.y);
    }          
    break;
}