在鼠标单击画布上更改文本

change text on mouseclick canvas

本文关键字:文本 鼠标 单击      更新时间:2023-09-26

我目前有文本显示"可用空间",悬停显示"单击此处预订自行车"。当用户单击画布时,颜色变为红色,但我如何使文本从"单击此处预订自行车"更改为"预订自行车"。

这是代码 https://jsfiddle.net/nayshal/j2y7jm4t/

<div id="canvas-wrap">
  <canvas id="canvas" width=150 height=100> </canvas>
    <p class="text">Click here to reserve bike</p>
    <p class="text1">Free Space</p>
<div id="overlay"></div>
</div>

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.rect(0, 0, 180, 100);
ctx.stroke();
ctx.fillStyle = "green";
ctx.fill();
document.addEventListener('click',mouseClick,false);
function mouseClick(e)
{  
ctx.fillStyle = "#FF0000";
ctx.fill();
}

你的想法在我看来毫无意义。您不会使用 HTML 在画布顶部添加文本!你应该像这样使用Javascript添加它:

ctx.font = "30px Verdana";
ctx.fillText("Hello World", 10, 50);

否则,使用画布是没有意义的。如果要在执行此操作后更改文本,则基本上需要删除所有内容并重新设置,因为fillText()将文本"种植"在画布上。让它粘住。它不是您可以编辑的对象,因此您需要刷新它并创建新文本。

https://jsfiddle.net/j2y7jm4t/2/

ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.fillStyle = "#000";
ctx.font = "20px Arial";
ctx.textAlign = 'center';
ctx.fillText("Bike reserved", 75, 50);

这有意义吗?


现在为了更改文本,您可以执行以下操作:

https://jsfiddle.net/j2y7jm4t/3/

首先将文本设置为默认值:

ctx.fillStyle = "#000";
ctx.font = "12px Arial";
ctx.textAlign = 'center';
ctx.fillText("Click here to reserve bike", 75, 50);

现在它会说

点击这里预订自行车

然后只需返回在单击功能中添加您需要执行的任何操作,如下所示:

ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.fillStyle = "#000";
ctx.fillText("Bike reserved", 75, 50);

有效吗?

在mouseclick事件中,您需要访问包含"单击此处预订自行车"文本的DOM元素。

document.getElementByClassName('text').innerHTML = "bike reserved"

将实现您所追求的,我建议使用ID(一次性标识符,而不是可以在元素之间共享的类)

e/- 我也相信你可能以错误的方式使用画布,<p>标签是一个 html 元素而不是画布的一部分,如果你想将文本绘制到画布中,请阅读这里:http://www.w3schools.com/canvas/canvas_text.asp