QML Canvas的簡單實用
阿新 • • 發佈:2018-11-08
QML提供一個和HTML5中一樣的Canvas畫布。這裡介紹一個Canvas的使用網站。
1.實現一個小球的自由落體
//自由落體 Canvas{ id : canvas width: 500; height: 500 property real gravity: 9.8 //重力加速度 property real droptime: 0; //下落時間 property real dropheigth: 0 onPaint: { var ctx = getContext("2d"); ctx.clearRect(0,0,width,height); ctx.beginPath() ctx.strokeRect(0,0,width,height) ctx.arc(50,dropheigth,30,0,Math.PI*2, false); ctx.closePath(); ctx.fill(); } Timer{ interval: 100; running: true; repeat: true onTriggered: { canvas.requestPaint(); droptime += 0.5; canvas.dropheigth = 0.5*gravity*droptime*droptime; if (canvas.dropheigth > canvas.height) droptime = 0; } } }
2.利用陰影實現發光體的效果,使用陰影的使用。
3.漸進色的使用//陰影 shadowBlur不能設定太大,太大的會卡的會很嚴重 //動畫效果,利用陰影實現發光體的效果 Canvas{ id : canvas width: 100; height: 100; property real xoffset: 19 property real voffset: -1 onPaint: { var ctx = getContext("2d"); ctx.clearRect(0,0,width,height); ctx.shadowColor = "rgb(255, 0, 0)"; // Red ctx.shadowBlur = 5; ctx.shadowOffsetX = xoffset; ctx.shadowOffsetY = 5; ctx.font = " 30px 微軟雅黑" //ctx.fillText("cehsi",20,20); ctx.beginPath() //ctx.strokeRect(0,0,width,height) ctx.arc(50,50,30,0,Math.PI*2, false); ctx.closePath(); ctx.fill(); } Timer{ interval: 500; running: true; repeat: true onTriggered: { canvas.requestPaint(); if (canvas.xoffset == -19) canvas.voffset = 1; if (canvas.xoffset == 19) canvas.voffset = -1; canvas.xoffset+= canvas.voffset; } } }
//漸進色測試 Canvas{ //anchors.fill: parent width: 100; height: 100 onPaint: { var ctx = getContext("2d"); ctx.clearRect(0,0,width,height); var px = width/2; var py = width/2; var r = Math.min(px,py); var col = ctx.createRadialGradient(px, py, 0, px, py, r); col.addColorStop(0, "darkRed"); col.addColorStop(0.6, Qt.rgba(1, 0, 0, 0.5)); col.addColorStop(1, Qt.rgba(1, 0, 0, 0)); ctx.fillStyle = col; //ctx.strokeStyle=Qt.rgba(1, 0, 0, 1) ctx.ellipse(0, 0, width, height); //ctx.stroke(); ctx.fill(); } }