gpt4 book ai didi

canvas - 如何用图像填充 Canvas 中的文本?

转载 作者:行者123 更新时间:2023-12-05 09:23:46 27 4
gpt4 key购买 nike

我最近一直在使用 HTML5 Canvas ,想知道是否有一种方法可以用图像而不是纯色来填充文本?

我现在可以得到这样的东西:

What I can do

但我需要文本看起来像(可以在 Photoshop 中完成):

Example

我读过很多次关于有时必须在第二个 Canvas 上渲染图像上的部分并将绘图导入主可见 Canvas 的内容,但其中大部分是关于给图像着色(不确定这是否适用于此处) .

为什么我需要这个:正如你所看到的,上面的 Controller 漂亮而 Shiny ,但文本却不是,客户希望我从不同的 Controller 外壳颜色中提取文本颜色,使其看起来尽可能逼真.

在搜索更多内容时,我碰巧找到了 this example ,这正是我想要的。但不幸的是,这个例子的问题是我需要以某种方式只导出图像的文本,我认为这是不可能的,所以它可以在没有黑色外层覆盖部分的情况下转置到新图像中 Controller 。

如果有人能给我正确的方向,无论多么复杂,我都将不胜感激。

附言这里如果 Controller 的绘制顺序:

  1. 外壳
  2. 正文
  3. 零件/背面
  4. 拇指杆
  5. 引导按钮
  6. ABXY 按钮
  7. 遮住 Controller (防止文本溢出)

最佳答案

您可以使用合成将不透明的文本像素替换为叠加图像

enter image description here

此代码使用 context.globalCompositeOperation="source-in"仅将文本像素替换为图像的相应像素:

// put text on canvas
ctx.beginPath();
ctx.font="72pt Verdana";
ctx.fillText("XBOX",10,100);
ctx.fill();


// use compositing to draw the background image
// only where the text has been drawn
ctx.beginPath();
ctx.globalCompositeOperation="source-in";
ctx.drawImage(img,0,0);

这是代码和 fiddle :http://jsfiddle.net/m1erickson/atM4m/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>

<script>
$(function(){

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

var img=document.createElement("img");
img.onload=function(){
draw();
}
img.src="http://images4.fanpop.com/image/photos/23400000/water-water-23444632-2048-1277.jpg";

function draw(x){

ctx.save();
ctx.beginPath();

// put text on canvas
ctx.font="72pt Verdana";
ctx.fillText("XBOX",10,100);
ctx.fill();


// use compositing to draw the background image
// only where the text has been drawn
ctx.beginPath();
ctx.globalCompositeOperation="source-in";
ctx.drawImage(img,0,0);
ctx.restore();
}





}); // end $(function(){});
</script>

</head>

<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

关于canvas - 如何用图像填充 Canvas 中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19268904/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com