在利用Canvas绘制文本的时候,可以指定文本不同的风格。
Context2D中和文本相关的方法有3个: fillText() , strokeText() , text();
使用方法就下面两种:
ctx.beginPath();
ctx.text(“stroken text” ,100 , 100);
ctx.stroke();
或者是另外的一种使用方法:
ctx.strokeText(“stroken text” , 200 ,100);
下面就通过一个具体的例子来学习下。
import QtQuick 2.2
Canvas{
width: 530;
height: 300;
id: root;
onPaint: {
var ctx = getContext("2d");
ctx.lineWidth = 2;
ctx.strokeStyle = "red";
ctx.font = " 42px sans-serif";
var gradient = ctx.createLinearGradient(0,0, width , height);
gradient.addColorStop( 0.0 , Qt.rgba(0 , 1 ,0 , 1));
gradient.addColorStop(1.0 , Qt.rgba(0,0, 1 , 1));
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.text("Fill Text on Path" , 10 , 50);
ctx.fill(); // 设置 ↑ 的text的风格为fill
ctx.fillText("Fill Text" , 10 , 100);
ctx.beginPath();
ctx.text("Stroke Text on Path" , 10 , 150);
ctx.stroke(); //设置 ↑ 的text风格为stroke
ctx.strokeText("Stroke Text" , 10 , 200);
ctx.beginPath();
ctx.text("Stroke and Fill Text on Path" , 10 , 250 );
ctx.stroke();
ctx.fill();
}
}