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

时间:2015-07-11 13:51:19

标签: javascript html5 canvas fonts

所以我试图让这个画布上有不同类型的文字,包括颜色。这就是我到目前为止所拥有的。

<!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>

2 个答案:

答案 0 :(得分:1)

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

class Person {
private $_firstName;
private $_lastName;

public function setFirstName($value) {
    $v = trim($value);
    $this->_firstName = empty($v) ? null : $v;
}

public funtion getFirstName() {
    return $this->_firstName;
}

public function setLasttName($value) {
    $v = trim($value);
    $this->_lastName = empty($v) ? null : $v;
}

public funtion getLastName() {
    return $this->_lastName;
}

答案 1 :(得分:1)

fillText

之前使用 fillStyle

检查此Fiddle