[英]HTML5 Canvas Text Stroke gives unwanted overlapping in chrome but works fine in Safari
Basic text stroke code.基本文本笔画代码。
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = 80;
var y = 110;
context.font = '100pt arial';
context.lineWidth = 37;
context.strokeStyle = "rgba(255,0,0,0.5)";
context.strokeText('Ho', x, y);
</script>
Output in Chrome and Firefox is : Chrome 和 Firefox 中的输出是:
The overlapping area between 'H' and 'o' is darker than non overlapping area. “H”和“o”之间的重叠区域比非重叠区域更暗。 I want to have same opacity/alpha for the stroke text.我希望笔画文本具有相同的不透明度/alpha。
I tried it in Safari on Mac system and there was not such a problem.我在 Mac 系统的 Safari 中尝试过,没有出现这样的问题。 In safari i got uniform opacity/alpha for both overlapping and non-overlapping region.在 safari 中,我得到了重叠和非重叠区域的统一不透明度/alpha。
I need to understand why this is happening in chrome and what should i do to have uniform opacity/alpha.我需要了解为什么在 chrome 中会发生这种情况,以及我应该怎么做才能获得统一的不透明度/alpha。
The behaviour is not what is to be expected, the strokeText call one would expect to be part of a single path, and would consider it a bug in both Chrome and Firefox.这种行为不是预期的,strokeText 调用会期望成为单个路径的一部分,并且会认为它是 Chrome 和 Firefox 中的错误。
Nevertheless you need a solution.尽管如此,您还是需要一个解决方案。 The only one I can think of is to create a second canvas.我唯一能想到的就是创建第二个画布。 Render the text without opacity on that canvas then render that canvas onto the original canvas using ctx.globalAlpha = 0.5
在画布上渲染没有不透明度的文本,然后使用ctx.globalAlpha = 0.5
将该画布渲染到原始画布上
Example.例子。
var canvas = document.createElement("canvas"); canvas.width = 500; canvas.height = 500; var ctx = canvas.getContext("2d"); document.body.appendChild(canvas); var x = 40; var y = 110; ctx.font = '100pt arial'; ctx.lineWidth = 20; ctx.fillRect(10,y,500,10); ctx.strokeStyle = "rgba(255,0,0,0.5)"; ctx.strokeText('Bad', x, y); var workCan = document.createElement("canvas"); workCan.width = canvas.width; workCan.height = canvas.height; var ctx1 = workCan.getContext("2d"); ctx1.font = '100pt arial'; ctx1.lineWidth = 20; ctx1.strokeStyle = "rgba(255,0,0,1)"; x = 40; y = 260; ctx1.strokeText('Good', x, y); ctx.fillRect(10,y,500,10); ctx.globalAlpha = 0.5; ctx.drawImage(workCan,0,0);
You can use plain CSS gradient with alpha values, and the alpha will not add up:您可以使用带有 alpha 值的普通 CSS 渐变,并且 alpha 不会相加:
background: -webkit-linear-gradient(top, rgba(10, 14, 15, 0.3), rgba(10, 14, 15, 0.3));
-webkit-background-clip: text;
-webkit-text-stroke: 1vw transparent;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.