考虑下面的代码,它允许您将表示为黑色圆圈的连续点插入到画布上。代码的目的是 用红线段连接每个连续点。
然而,代码给了我一个看起来像这样的画布
只有红色段加入了第一个和第二个点。其他任何一点都没有加入细分市场。我该如何解决这个问题?
这是QML代码
import QtQuick 2.7
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window{
id: root
width: 640
height: 480
visible: true
Canvas {
id: mycanvas
width: 500
height: 500
function clear() {
var ctx = getContext("2d");
ctx.reset();
mycanvas.requestPaint();
}
Path {
id: myPath
startX: 0; startY: 100
PathLine { x: 400; y: 500 }
}
property var arrpoints : []
onPaint: {
var context = getContext("2d");
// Render all the points as small black-circles
context.strokeStyle = Qt.rgba(0, 1, 1, 0)
for(var i=0; i < arrpoints.length; i++){
var point= arrpoints[i]
context.ellipse(point["x"], point["y"], 10, 10)
}
context.fill()
context.stroke()
// Join successive points with red segments
for (var j=1 ; j < arrpoints.length ; j++){
var start = arrpoints[j-1]
var end = arrpoints[j]
context.beginPath();
context.lineWidth = 2;
context.moveTo(start["x"], start["y"]);
context.strokeStyle = "red"
context.lineTo(end["x"], end["y"]);
}
context.stroke();
}
MouseArea {
id: mymouse
anchors.fill: parent
onClicked: {
mycanvas.arrpoints.push({"x": mouseX, "y": mouseY})
mycanvas.requestPaint()
console.log( mycanvas.arrpoints )
}
}
}
Button {
text: "Clear Points"
anchors.top : mycanvas.bottom
onClicked: {
mycanvas.arrpoints.length = 0
mycanvas.clear()
console.log( mycanvas.arrpoints )
}
}
}//Window
答案 0 :(得分:1)
对象椭圆(真实x,真实y,真实w,真实h)
在由其定义的边界矩形内创建椭圆 在(x,y),宽度w和高度h的左上角,并将其添加到 路径作为封闭的子路径。
椭圆由顺时针曲线,起点和终点组成 零度(3点钟位置)。
也就是说,椭圆被绘制成由位置(x,y)和大小w,h确定的矩形,因此我们必须使用鼠标点和半径获得topLeft点。
对于行,没有必要为每一行创建路径,您只需使用路径,然后创建该行并移动到下一个点,如下所示:
import QtQuick 2.7
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window{
id: root
width: 640
height: 480
visible: true
Canvas {
id: mycanvas
width: 500
height: 500
function clear() {
var ctx = getContext("2d");
ctx.reset();
mycanvas.requestPaint();
}
Path {
id: myPath
startX: 0; startY: 100
PathLine { x: 400; y: 500 }
}
property real radius: 10
property var arrpoints : []
onPaint: {
var context = getContext("2d");
context.save()
if(arrpoints.length > 0){
for(var i=0; i < arrpoints.length; i++){
var point= arrpoints[i]
context.ellipse(point["x"]-radius, point["y"]-radius, 2*radius, 2*radius)
}
context.strokeStyle = Qt.rgba(0, 1, 1, 0)
context.fill()
context.stroke()
context.beginPath()
var start = arrpoints[0]
context.moveTo(start["x"], start["y"])
for(var j=1; j < arrpoints.length; j++){
var end= arrpoints[j]
context.lineTo(end["x"], end["y"])
context.moveTo(end["x"], end["y"])
}
context.closePath()
context.strokeStyle = "red"
context.lineWidth = 2;
context.stroke()
}
context.restore()
}
MouseArea {
id: mymouse
anchors.fill: parent
onClicked: {
mycanvas.arrpoints.push({"x": mouseX, "y": mouseY})
mycanvas.requestPaint()
}
}
}
Button {
text: "Clear Points"
anchors.top : mycanvas.bottom
onClicked: {
mycanvas.clear()
console.log( mycanvas.arrpoints )
}
}
}//Window