Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rendering issue when using physical unit mm #159

Open
Jlowzow opened this issue Jul 11, 2022 · 2 comments
Open

Rendering issue when using physical unit mm #159

Jlowzow opened this issue Jul 11, 2022 · 2 comments

Comments

@Jlowzow
Copy link

Jlowzow commented Jul 11, 2022

When using mm as the unit for my sketch, I'm getting a rendering issue when drawing a line with lineWidth < 2.
This looks similar to when drawing a line that is smaller than 2 pixels, even though a mm is a much bigger unit than the pixel.

Will I have to use px as the unit, and manually scale to prepare for a print?

@Jlowzow
Copy link
Author

Jlowzow commented Jul 11, 2022

It seems the issue stems from drawing on a secondary canvas, and then using context.drawImage(), to place it on the canvas.

@mattdesl
Copy link
Owner

If you have a second canvas, you will probably want to set the size and scale to be the same. Example:

const canvasSketch = require('canvas-sketch');

const settings = {
  dimensions: [ 5, 5 ],
  units: 'cm',
  pixelsPerInch: 300,
  scaleToView: true
};

const sketch = () => {
  const offCanvas = document.createElement('canvas')
  const offContext = offCanvas.getContext('2d');

  return ({ context, width, height, canvasWidth, canvasHeight, scaleX, scaleY }) => {
    offCanvas.width = canvasWidth;
    offCanvas.height = canvasHeight;
    offContext.save();
    offContext.scale(scaleX, scaleY);

    // Now use the context as you'd render your sketch typically
    const grad = offContext.createLinearGradient(0, 0, width, height);
    grad.addColorStop(0, 'tomato')
    grad.addColorStop(1, 'palegreen')
    offContext.strokeStyle = grad;
    offContext.beginPath();
    offContext.lineTo(2, 2)
    offContext.lineTo(width-2, height-2)
    offContext.lineWidth = 2;
    offContext.lineCap = 'round';
    offContext.stroke();

    offContext.restore();


    context.fillStyle = 'white';
    context.fillRect(0, 0, width, height);

    context.drawImage(offCanvas, 0, 0, width, height);
    context.globalCompositeOperation = 'multiply';
    context.drawImage(offCanvas, width/4, width/4, width/2, height/2);
    context.globalCompositeOperation = 'source-over';
  };
};

canvasSketch(sketch, settings);

Let me know if that fixes things.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants