canvas2svg icon indicating copy to clipboard operation
canvas2svg copied to clipboard

Implement CanvasTransform Interface

Open zenozeng opened this issue 4 years ago • 0 comments

Current transformation implementation adds a <g> element and set <g>'s transform attribute with string concatenation of rotate, matrix, rotate, scale.

This pull request implements CanvasTransform interface using DOMMatrix and SVG's matrix(a b c d e f) transform function. Compared to adding string concatenation results to transform attribute of <g> element, it is more reliable to use the transformation matrix which DOMMatrix API calculates and applied directly to <path>, <rect> and other elements every time.

Example

ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
ctx.transform(2, 0, 0, 2, 0, 0);
ctx.rotate(Math.PI / 6);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.lineTo(100, 0);
ctx.fill();
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.rotate(-Math.PI / 6);
ctx.lineTo(100, 0);
ctx.fill();

Rendered in Canvas:

44171C71-CD0D-4A57-924A-BE4B80B546C3

Rendered with v1.0.19’s implementation:

37722174-E2EF-4E33-BEBC-5965E9C8E9B8 9C49CEE7-0AA3-4E77-943C-8DA47ACADC07

Rendered with this pull request's implementation:

2FAB35B0-9F38-48D5-8D40-D30FE286EDD5

For lineTo, bezierCurveTo, quadraticCurveTo, each step’s point x and y were now calculated based on current transformation matrix.

New methods

This pull request also implemented 3 missing methods defined in CanvasTransform interface:

  • ctx.prototype.setTransform(a, b, c, d, e, f): SetTransform changes the current transformation matrix to the matrix given by the arguments as described below.
  • ctx.prototype.getTransform(): Returns a copy of the current transformation matrix, as a newly created DOMMAtrix Object.
  • ctx.prototype.resetTransform(): ResetTransform resets the current transformation matrix to the identity matrix.

Reference

  • https://html.spec.whatwg.org/multipage/canvas.html#canvastransform
  • https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform
  • https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setTransform
  • https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/resetTransform
  • https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-scale
  • https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/rotate
  • https://www.w3.org/TR/css-transforms-1
  • https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/translate
  • https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/transform

zenozeng avatar Jun 13 '21 15:06 zenozeng