简体   繁体   English

如何在HTML画布中使用不同颜色的文本

[英]How do I have different colours of text in an HTML canvas

So I'm trying to make this canvas have different types of text on it including colours. 因此,我试图使此画布上具有不同类型的文本,包括颜色。 Here what I have so far. 这是我到目前为止所拥有的。

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="400" height="200" style=" border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
window.onload = function(){
     var canvas = document.getElementById("myCanvas");
     var context = canvas.getContext("2d");
     var imageObj = new Image();
     imageObj.onload = function(){
         context.drawImage(imageObj, 0, 0);
         context.font = "40pt Calibri";
         context.fillText("My TEXT!", 50, 100);
     };
     imageObj.src = "Assets/Background2.png"; 
};
</script>
</body>
</html>

您每次需要更改字体颜色时,只需使用fillStyle方法:

context.fillStyle = 'red';

Use fillStyle before fillText fillText之前使用fillStyle

Check this Fiddle 检查这个Fiddle

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

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