Porting from HTML5 Canvas

Porting from an HTML5 canvas to a QML canvas is fairly easy. In this chapter we will look at the example below and do the conversion.

Spirograph

We use a spirographPorting from HTML5 Canvas - 图3 (opens new window) example from the Mozilla project as our foundation. The original HTML5 was posted as part of the canvas tutorialPorting from HTML5 Canvas - 图4 (opens new window).

There were a few lines we needed to change:

  • Qt Quick requires you to declare a variable, so we needed to add some var declarations

    1. for (var i=0;i<3;i++) {
    2. ...
    3. }
  • We adapted the draw method to receive the Context2D object

    1. function draw(ctx) {
    2. ...
    3. }
  • We needed to adapt the translation for each spiro due to different sizes

    1. ctx.translate(20+j*50,20+i*50);

Finally, we completed our onPaint handler. Inside we acquire a context and call our draw function.

  1. onPaint: {
  2. var ctx = getContext("2d");
  3. draw(ctx);
  4. }

The result is a ported spiro graph graphics running using the QML canvas.

image

As you can see, with no changes to the actual logic, and relatively few changes to the code itself, a port from HTML5 to QML is possible.

Glowing Lines

Here is another more complicated port from the W3C organization. The original pretty glowing linesPorting from HTML5 Canvas - 图6 (opens new window) has some pretty nice aspects, which makes the porting more challenging.

image

  1. <!DOCTYPE HTML>
  2. <html lang="en">
  3. <head>
  4. <title>Pretty Glowing Lines</title>
  5. </head>
  6. <body>
  7. <canvas width="800" height="450"></canvas>
  8. <script>
  9. var context = document.getElementsByTagName('canvas')[0].getContext('2d');
  10. // initial start position
  11. var lastX = context.canvas.width * Math.random();
  12. var lastY = context.canvas.height * Math.random();
  13. var hue = 0;
  14. // closure function to draw
  15. // a random bezier curve with random color with a glow effect
  16. function line() {
  17. context.save();
  18. // scale with factor 0.9 around the center of canvas
  19. context.translate(context.canvas.width/2, context.canvas.height/2);
  20. context.scale(0.9, 0.9);
  21. context.translate(-context.canvas.width/2, -context.canvas.height/2);
  22. context.beginPath();
  23. context.lineWidth = 5 + Math.random() * 10;
  24. // our start position
  25. context.moveTo(lastX, lastY);
  26. // our new end position
  27. lastX = context.canvas.width * Math.random();
  28. lastY = context.canvas.height * Math.random();
  29. // random bezier curve, which ends on lastX, lastY
  30. context.bezierCurveTo(context.canvas.width * Math.random(),
  31. context.canvas.height * Math.random(),
  32. context.canvas.width * Math.random(),
  33. context.canvas.height * Math.random(),
  34. lastX, lastY);
  35. // glow effect
  36. hue = hue + 10 * Math.random();
  37. context.strokeStyle = 'hsl(' + hue + ', 50%, 50%)';
  38. context.shadowColor = 'white';
  39. context.shadowBlur = 10;
  40. // stroke the curve
  41. context.stroke();
  42. context.restore();
  43. }
  44. // call line function every 50msecs
  45. setInterval(line, 50);
  46. function blank() {
  47. // makes the background 10% darker on each call
  48. context.fillStyle = 'rgba(0,0,0,0.1)';
  49. context.fillRect(0, 0, context.canvas.width, context.canvas.height);
  50. }
  51. // call blank function every 50msecs
  52. setInterval(blank, 40);
  53. </script>
  54. </body>
  55. </html>

In HTML5 the Context2D object can paint at any time on the canvas. In QML it can only point inside the onPaint handler. The timer in usage with setInterval triggers in HTML5 the stroke of the line or to blank the screen. Due to the different handling in QML, it’s not possible to just call these functions, because we need to go through the onPaint handler. Also, the color presentations need to be adapted. Let’s go through the changes on by one.

Everything starts with the canvas element. For simplicity, we just use the Canvas element as the root element of our QML file.

  1. import QtQuick
  2. Canvas {
  3. id: canvas
  4. width: 800; height: 450
  5. ...
  6. }

To untangle the direct call of the functions through the setInterval, we replace the setInterval calls with two timers which will request a repaint. A Timer is triggered after a short interval and allows us to execute some code. As we can’t tell the paint function which operation we would like to trigger we define for each operation a bool flag request an operation and trigger then a repaint request.

Here is the code for the line operation. The blank operation is similar.

  1. ...
  2. property bool requestLine: false
  3. Timer {
  4. id: lineTimer
  5. interval: 40
  6. repeat: true
  7. triggeredOnStart: true
  8. onTriggered: {
  9. canvas.requestLine = true
  10. canvas.requestPaint()
  11. }
  12. }
  13. Component.onCompleted: {
  14. lineTimer.start()
  15. }
  16. ...

Now we have an indication which (line or blank or even both) operation we need to perform during the onPaint operation. As we enter the onPaint handler for each paint request we need to extract the initialization of the variable into the canvas element.

  1. Canvas {
  2. ...
  3. property real hue: 0
  4. property real lastX: width * Math.random();
  5. property real lastY: height * Math.random();
  6. ...
  7. }

Now our paint function should look like this:

  1. onPaint: {
  2. var context = getContext('2d')
  3. if(requestLine) {
  4. line(context)
  5. requestLine = false
  6. }
  7. if(requestBlank) {
  8. blank(context)
  9. requestBlank = false
  10. }
  11. }

The line function was extracted for a canvas as an argument.

  1. function line(context) {
  2. context.save();
  3. context.translate(canvas.width/2, canvas.height/2);
  4. context.scale(0.9, 0.9);
  5. context.translate(-canvas.width/2, -canvas.height/2);
  6. context.beginPath();
  7. context.lineWidth = 5 + Math.random() * 10;
  8. context.moveTo(lastX, lastY);
  9. lastX = canvas.width * Math.random();
  10. lastY = canvas.height * Math.random();
  11. context.bezierCurveTo(canvas.width * Math.random(),
  12. canvas.height * Math.random(),
  13. canvas.width * Math.random(),
  14. canvas.height * Math.random(),
  15. lastX, lastY);
  16. hue += Math.random()*0.1
  17. if(hue > 1.0) {
  18. hue -= 1
  19. }
  20. context.strokeStyle = Qt.hsla(hue, 0.5, 0.5, 1.0);
  21. // context.shadowColor = 'white';
  22. // context.shadowBlur = 10;
  23. context.stroke();
  24. context.restore();
  25. }

The biggest change was the use of the QML Qt.rgba() and Qt.hsla() functions, which required to adopt the values to the used 0.0 … 1.0 range in QML.

Same applies to the blank function.

  1. function blank(context) {
  2. context.fillStyle = Qt.rgba(0,0,0,0.1)
  3. context.fillRect(0, 0, canvas.width, canvas.height);
  4. }

The final result will look similar to this.

image