1. 基础绘制
技巧:使用Context2D
的API绘制基本图形(直线、矩形、圆形等)。
Canvas {
id: canvas
width: 200; height: 200
onPaint: {
var ctx = getContext("2d");
ctx.strokeStyle = "red";
ctx.lineWidth = 2;
// 绘制矩形
ctx.strokeRect(10, 10, 50, 50);
// 绘制圆形
ctx.beginPath();
ctx.arc(100, 100, 30, 0, 2 * Math.PI);
ctx.stroke();
}
}
2. 路径操作
技巧:通过beginPath()
和closePath()
管理复杂路径,使用贝塞尔曲线或圆弧。
onPaint: {
var ctx = getContext("2d");
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.quadraticCurveTo(75, 25, 100, 50); // 二次贝塞尔曲线
ctx.bezierCurveTo(110, 60, 130, 40, 150, 50); // 三次贝塞尔曲线
ctx.stroke();
}
3. 渐变与阴影
技巧:使用线性/径向渐变填充,添加阴影提升立体感。
onPaint: {
var ctx = getContext("2d");
// 线性渐变
var gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, "blue");
gradient.addColorStop(1, "green");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 200);
// 阴影
ctx.shadowColor = "gray";
ctx.shadowBlur = 10;
ctx.fillStyle = "orange";
ctx.fillRect(50, 50, 100, 100);
}
4. 图像处理
技巧:异步加载图像,使用drawImage
绘制。
Canvas {
Image {
id: sourceImage
source: "image.png"
onStatusChanged: if (status == Image.Ready) canvas.requestPaint();
}
onPaint: {
var ctx = getContext("2d");
ctx.drawImage(sourceImage, 0, 0);
}
}
5. 动画与动态更新
技巧:结合Timer
或Animation
实现动态效果。
Timer {
interval: 16 // ~60 FPS
running: true
repeat: true
onTriggered: {
angle += 0.1;
canvas.requestPaint();
}
}
onPaint: {
var ctx = getContext("2d");
ctx.clearRect(0, 0, width, height);
ctx.translate(100, 100);
ctx.rotate(angle);
ctx.fillRect(-25, -25, 50, 50);
}
6. 性能优化
- 缓存静态内容:对不变的元素仅绘制一次。
- 离屏渲染:预渲染复杂图形到隐藏的Canvas。
- 减少状态切换:使用
save()
和restore()
管理绘图状态。
Canvas {
id: offscreenCanvas
visible: false
// ...预渲染内容...
}
// 主Canvas中直接绘制离屏内容
onPaint: {
var ctx = getContext("2d");
ctx.drawImage(offscreenCanvas, 0, 0);
}
7. 高分辨率适配
技巧:根据设备像素比例调整Canvas尺寸避免模糊。
Canvas {
width: 200 * Qt.application.devicePixelRatio
height: 200 * Qt.application.devicePixelRatio
renderTarget: Canvas.FramebufferObject // 高DPI支持
}
8. 转换与合成
技巧:使用translate
、rotate
、scale
变换坐标系,或通过globalCompositeOperation
实现混合效果。
onPaint: {
var ctx = getContext("2d");
ctx.translate(100, 100);
ctx.scale(1.5, 1.5);
ctx.globalCompositeOperation = "multiply"; // 颜色叠加效果
ctx.fillStyle = "blue";
ctx.fillRect(-50, -50, 100, 100);
}
9. 事件交互
技巧:监听鼠标/触摸事件实现交互式绘图。
MouseArea {
anchors.fill: parent
onPressed: canvas.drawPoint(mouse.x, mouse.y)
}
function drawPoint(x, y) {
var ctx = getContext("2d");
ctx.beginPath();
ctx.arc(x, y, 5, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
}
掌握这些技巧后,您可灵活运用QML Canvas实现复杂绘图需求,结合QML的声明式语法和JavaScript的动态能力,打造丰富的可视化界面。