清除画布形状中的文本 [英] Clean text from canvas shapes

查看:46
本文介绍了清除画布形状中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How I clean text from canvas shape ? this my code:

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

小提琴

推荐答案

只需重构一下代码-

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

Extract the lines which draws the circle into a single function which takes one of those circle objects as an argument:

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();
}

然后在循环中用这条线(在按下圆形对象之后)替换它们原来来自的那些线:

Then replace those lines which they came from originally, in the loop with this line (after the circle object has been pushed):

drawCircle(circles[circles.length-1]);   // draw last added circle

现在,您可以通过修改代码(在此处打​​开和关闭文本)来在点击事件中使用此功能:

Now you can use this function in your click events by modifying the code (here, it toggles text on and off):

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;
}

修改过的小提琴

Modified fiddle

使用此方法仅需注意:这将使圆圈相互重绘.随着时间的流逝,由于边缘上增加了抗锯齿功能,线条将开始显得锯齿状.因此,最好先完全清除画布,然后再重新绘制它们.但我会将其留给您练习:.:-)

Just a note with this approach: this will redraw the circles on top of each other. Over time the lines will start to look jaggy due to the added anti-aliasing on the edges. For this reason a full clear of the canvas is better, and then redraw them all. But I'll leave that as an exercise for you.. :-)

这篇关于清除画布形状中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆