简体   繁体   English

对于 html canvas,如何使用带有文本作为路径的 clip()?

[英]For html canvas, how to use clip() with a text as a path?

I wrote the following code which is similar to my objective but falls short;我编写了以下与我的目标相似但不足的代码; because I want to fill inside the text in multiple colors;因为我想在多个colors里面填写文字; currently only in #FF00FF.目前仅在#FF00FF。

Playground操场

I think the problem is that I don't know how to use the text "ABC" as the clipping path.我认为问题在于我不知道如何使用文本“ABC”作为剪切路径。 Please show me how to do it, or any answer equivalent for my objective.请告诉我如何做到这一点,或任何与我的目标相当的答案。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas</title>
<script type="text/javascript">
function test() {
  var canvas = document.getElementById('sample');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    ctx.beginPath();
    for(let i=1;i<100;i++){
       //mock1: ctx.fillStyle = "rgb(" + [i, i, i] + ")";
       ctx.moveTo(0,5*i);
       ctx.lineTo(380,5*i);
       ctx.lineTo(300,5*i+3);
       ctx.lineTo(0,5*i+3);
       ctx.lineTo(0,5*i);
       }
    ctx.closePath();

    ctx.clip();

    ctx.font = "bold 72px 'Sans-selif'";
    ctx.fillStyle = "#FF00FF";  
    ctx.fillText("ABC", 90, 60);
    
    
  }
}
</script>
</head>
<body onLoad="test()">
<h2>Canvas</h2>
<canvas width="300" height="150" id="sample" style="background-color:yellow;">
</canvas>
</body>
</html>

The 2DCanvas API unfortunately doesn't expose the text's contour in a way it could be used as a Path2D or in methods like clip() or isPointInPath() .不幸的是,2DCanvas API 没有以可用作 Path2D 或在诸如clip()isPointInPath()之类的方法中的方式暴露文本的轮廓。
However for what you wish to do, you don't need a path, this can be done by using compositing instead of clipping:但是,对于您想要做的事情,您不需要路径,这可以通过使用合成而不是剪辑来完成:

 var canvas = document.getElementById('sample'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); // draw the full lines first ctx.beginPath(); for (let i = 1; i < 100; i++) { ctx.moveTo(0, 5 * i); ctx.lineTo(380, 5 * i); ctx.lineTo(300, 5 * i + 3); ctx.lineTo(0, 5 * i + 3); ctx.lineTo(0, 5 * i); } ctx.fillStyle = "#00FF00"; ctx.fill(); // with this mode // every previous pixel that is not under the next drawing // will get cleared ctx.globalCompositeOperation = "destination-atop" ctx.font = "bold 72px 'Sans-serif'"; ctx.fillStyle = "#FF00FF"; ctx.fillText("ABC", 90, 60); // reset to default mode ctx.globalCompositeOperation = "source-over" }
 <canvas width="300" height="150" id="sample" style="background-color:yellow;"></canvas>

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

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