javascript - 穿过带有文本/无图像的 Canvas 元素

标签 javascript html css canvas transparency

我想制作一个元素,其中文本是透明的,而 div 的其余部分是实心的,这样如果它的位置固定,您可以透过文本看到背景。

我通常只为此使用 alpha 映射图像,但是,我需要用户随心所欲地更改此文本,以便无论元素中的文本是什么,它都是透明的。尽管您不能使用普通的 div,这里的关键是在包含文本的元素上具有实际的背景颜色。

我对 Canvas 元素很陌生,但我想知道是否可以使用 Canvas 元素,如果可以,您能给我指明正确的方向吗?

最佳答案

是的,你可以用 Canvas 做到这一点。你可以使用 rgba(red,blue,green,transparency_value) 在 Canvas 中绘制具有透明度的文本

HTML:

<canvas id="mycanvas" width="200" height="200" style="width:200px; height:200px; border:1px solid;">
</canvas>

脚本:

canvas = document.getElementById('mycanvas');
ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.fillStyle = '#992200';
ctx.rect(0,0,canvas.width,canvas.height);
ctx.fill();
ctx.closePath();

ctx.fillStyle = 'rgba(255,255,255,1)';
ctx.font = '10px verdana';
ctx.textAlign = 'center';
ctx.fillText("No transparency",canvas.width/2,10);

ctx.fillStyle = 'rgba(255,255,255,0.5)';
ctx.font = '10px verdana';
ctx.textAlign = 'center';
ctx.fillText("This is Transparent[0.5]",canvas.width/2,canvas.height/2);

ctx.fillStyle = 'rgba(255,255,255,0.25)';
ctx.font = '10px verdana';
ctx.textAlign = 'center';
ctx.fillText("This is Transparent[0.25]",canvas.width/2,canvas.height - 10);

Live Demo

注意:设置rgba()应该是一个字符串(Mean应该用引号括起来)

  1. 了解 fillText()
  2. 了解 fillStyle
  3. 了解 textAlign

关于javascript - 穿过带有文本/无图像的 Canvas 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15756753/

相关文章:

javascript - 哪些浏览器支持 globalStorage?

javascript - 在尝试实现 Google 提要时如何解决我的 "' google' is undefined"错误?

javascript - 视频覆盖的 Bootstrap 导航栏 - 如何用不透明背景覆盖它?

html - 向右浮动元素不完全向右浮动

html - 在我的下拉菜单上添加第三层

javascript - Grails 和 css/javascript 库

java - 检索正确(完整)的 html

c# - 如何在 c# 中访问 Office365 Sharepoint (2013) 新闻/公告等文档以及 CSS 内容?

jquery - 如何使用 HTML/CSS 使按钮可点击?它需要与图像上的标题一起居中

javascript - 在 for 循环中查询 Youtube 的标题仅显示第一项