我可以在HTML5 Canvas中通过字符文本颜色吗? [英] Can I do by character text color in HTML5 Canvas?

查看:235
本文介绍了我可以在HTML5 Canvas中通过字符文本颜色吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在HTML Canvas中我可以使用ctx.fillStyle ='red'来设置一行文本的颜色,这很棒。我想做的是能够通过字母设置颜色,只需要绘制一次字。

In HTML Canvas I can set the color of a line of text using ctx.fillStyle = 'red', which is great. What I'm trying to do is by able to set the color by letter, with only having to draw the word once.

因此,如果文本是'Hello different colors!',是否有一种方法可以使字母H为红色,而文本的其余部分为白色?

So if the text is 'Hello different colors!', is there a way I can make the letter H red, but the rest of the text white?

推荐答案

我给你这个解决方法。基本上你每次输出一个字符一个字符,并使用内置的 measureText()函数来确定每个字母的宽度绘制。然后我们偏移了我们想要绘制的位置相同的量。

I present you this workaround. Basically you output your text one char at a time, and use inbuilt measureText() function to determine the width of each letter asif it was drawn. Then we offset the position where we wanted to draw by that same amount. You can modify this snippet, to produce the effect you want.

假设我们有这样的HTML:

Suppose we have HTML like so:

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

和Javascript一样:

And Javascript like so:

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

function randomColor(){
    var r = Math.floor(Math.random()*256);
    var g = Math.floor(Math.random()*256);
    var b = Math.floor(Math.random()*256);
    return "rgb("+ r + "," + g + "," + b +")";
}

function texter(str, x, y){
    for(var i = 0; i <= str.length; ++i){
        var ch = str.charAt(i);
        ctx.fillStyle = randomColor();
        ctx.fillText(ch, x, y);
        x += ctx.measureText(ch).width;
    }
}

texter("What's up?", 10, 30);

我们会得到一个输出:

We'd get an output:

在操作中检查 at jFiddle 。我使用了最新的Chrome。

Check it out in action at jFiddle. I used latest Chrome.

这篇关于我可以在HTML5 Canvas中通过字符文本颜色吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆