import QtQuick 2.4 import QtQuick.Controls 2.5 import QtQuick.Window 2.3 Window { visible: true width: 640 height: 480 title: qsTr("Hello World") Canvas { id: canvas width: parent.width height: parent.height // 绘制网格 onPaint: { var ctx = getContext("2d"); ctx.lineWidth = 1; ctx.strokeStyle = "lightgray"; for (var x = 10; x < canvas.width; x += 10) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, canvas.height); ctx.stroke(); } for (var y = 10; y < canvas.height; y += 10) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(canvas.width, y); ctx.stroke(); } } function drawRectangle() { var ctx = canvas.getContext("2d"); // 修正获取上下文对象的代码 var startX, startY; canvas.onMousePress = function(event) 这里的canvas.onMousePress出现了错误,报错信息为Error: Cannot assign to non-existent property "onMousePress",应该怎么修改
时间: 2024-02-10 09:21:17 浏览: 30
Canvas并没有onMousePress属性,所以你需要使用Canvas的mouse事件来实现鼠标事件的处理。你可以使用Canvas的onMouseXxx事件(如onMousePressed、onMouseMoved、onMouseReleased)来处理鼠标事件。你可以按照以下步骤修改代码:
1. 删除canvas.onMousePress = function(event)这一行代码。
2. 在Canvas中添加onMousePressed事件处理函数:
onMousePressed: {
var ctx = canvas.getContext("2d");
startX = mouse.x;
startY = mouse.y;
}
3. 在Canvas中添加onMouseMoved事件处理函数:
onMouseMoved: {
if (mouse.buttonDown) {
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 重绘网格
for (var x = 10; x < canvas.width; x += 10) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();
}
for (var y = 10; y < canvas.height; y += 10) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.stroke();
}
// 绘制矩形
var endX = mouse.x;
var endY = mouse.y;
var width = endX - startX;
var height = endY - startY;
ctx.fillStyle = "lightblue";
ctx.fillRect(startX, startY, width, height);
}
}
4. 在Canvas中添加onMouseReleased事件处理函数:
onMouseReleased: {
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 重绘网格
for (var x = 10; x < canvas.width; x += 10) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();
}
for (var y = 10; y < canvas.height; y += 10) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.stroke();
}
// 绘制矩形
var endX = mouse.x;
var endY = mouse.y;
var width = endX - startX;
var height = endY - startY;
ctx.fillStyle = "lightblue";
ctx.fillRect(startX, startY, width, height);
}
这样就可以通过鼠标绘制矩形了。