简体   繁体   English

在鼠标悬停在画布上显示文本

[英]Display text on Canvas in Mouse over

Currently, I'm working on Below Example https://codepen.io/jkiss/pen/OVEeqK here I'm changed the code to display on the canvas 目前,我正在研究以下示例https://codepen.io/jkiss/pen/OVEeqK,在这里我更改了代码以显示在画布上

 var canvas = document.getElementById('nokey');
   var ctx = canvas.getContext('2d');
  ctx.fillText("StacOverFlow",30,80);

But I'm not able to display the text by using above code. 但是我无法使用上面的代码显示文本。 Could any one please help to display the text. 任何人都可以帮助显示文本。

in your example https://codepen.io/jkiss/pen/OVEeqK , you have to add some code to render function like following: 在示例https://codepen.io/jkiss/pen/OVEeqK中 ,您必须添加一些代码来呈现函数,如下所示:

live example: https://codepen.io/siamand/pen/BdPBMq 实时示例: https //codepen.io/siamand/pen/BdPBMq

// Render
function render(){
    ctx.clearRect(0, 0, can_w, can_h);

    renderBalls();

    renderLines();

    updateBalls();

    addBallIfy();

    addCustomStuff();


    window.requestAnimationFrame(render);
}

function addCustomStuff(){
   //if(mouse_in){  // IF condition for show text when mouse_in
      ctx.fillStyle = 'red';
      ctx.fillText("StackOverflow",mouse_ball.x,mouse_ball.y);
   //}
}

you need to add the following html code: 您需要添加以下html代码:

<canvas id="nokey" width="800" height="800"> Your Browser Don't Support Canvas, Please Download Chrome ^_^`` </canvas>

This is because when you call var canvas = document.getElementById('nokey'); 这是因为当您调用var canvas = document.getElementById('nokey'); you are trying to get the canvas named 'nokey' in your example. 您尝试在示例中获取名为“ nokey”的画布。

You need to use ctx.fillStyle and ctx.font also to display font on canvas. 您还需要使用ctx.fillStylectx.font在画布上显示字体。

 var canvas = document.getElementById('nokey'), can_w = parseInt(canvas.getAttribute('width')), can_h = parseInt(canvas.getAttribute('height')), ctx = canvas.getContext('2d'); var ctx = canvas.getContext('2d'); ctx.fillStyle = "blue"; ctx.font = "bold 16px Arial"; ctx.fillText("StackOverFlow", 30, 80); 
 <canvas id="nokey" width="800" height="800"> Your Browser Don't Support Canvas, Please Download Chrome ^_^`` </canvas> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM