CBR
CBR

Reputation: 29

Javascript canvas. Fixed linewidth independent of the transformation

I am trying to draw a graph in a simple (x, y) plane.

I am using canvas transform to transform my coordinate system.

I am looking for a method to draw the 'linewidth' as a fixed pixel width independent of the x/y scale.

The problem is when x/y is large, the line width along x or y disappears or it is deformed because the line width is scaled relative to the x and y scale.

See example:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var y_scale=10
ctx.transform(1, 0, 0, 1/y_scale, 0, 0);
ctx.lineWidth = 10;
ctx.strokeRect(20, 20, 80, 100*y_scale);

Is there a way to fix the width independent of the transformation?

Of course I can do my own transformation matrix but I would rather not.

Upvotes: 1

Views: 1381

Answers (2)

user1693593
user1693593

Reputation:

Instead of scaling the context you could scale your point series - no need for a complete matrix solution. This way you are just altering the "path" and not the rendering result.

var scale = 10;
var newPoints = scalePoints(points, scale);  // scale or inverse: 1/scale

... plot new points here at the line-width you wish

// example function
function scalePoints(points, scale) {
    var newPoints = [];
    points.forEach(function(p) { newPoints.push(p * scale) });
    return newPoints
}

Modify as needed.

Upvotes: 0

Timur Bilalov
Timur Bilalov

Reputation: 3692

Same question: html5 canvas prevent linewidth scaling

Solution:

  1. Apply transformation
  2. Define path
  3. Restore transformation
  4. Stroke path

Code:

var y_scale=10;

ctx.beginPath();
ctx.save(); //save context
ctx.transform(1, 0, 0, 1 / y_scale, 0, 0);
ctx.rect(20, 20, 80, 100 * y_scale); // define rect
ctx.restore(); //restore context 

ctx.lineWidth = 10;
ctx.stroke(); //stroke path

See example: https://jsfiddle.net/aj3sn7yv/2/

Upvotes: 5

Related Questions