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

Setting width/height of canvas doesn't work #329

Open
Pingou opened this issue May 1, 2024 · 2 comments
Open

Setting width/height of canvas doesn't work #329

Pingou opened this issue May 1, 2024 · 2 comments

Comments

@Pingou
Copy link

Pingou commented May 1, 2024

If you set a custom width/height to the canvas, then use toDataURL, the image exported is wrong/not the same as the image shown.

Example:

`render() {

const canvasWidth = 900
const canvasHeight = 1280
const viewWidth = 300
const viewHeight = 500
var width = viewWidth
var height = viewHeight

return (
  <View style={{flex:1}}>

  <Canvas
        pointerEvents={'none'}
        style={{ width: width, height: height, borderWidth:1}}
        ref={(canvas) => {
          this.canvas = canvas;
          if (canvas && canvas.height != canvasHeight) {

            canvas.width = canvasWidth;
            canvas.height = canvasHeight;
            
            const context = canvas.getContext('2d');
            this.canvasScaleWidth =   canvasWidth / viewWidth;
            this.canvasScaleHeight =  canvasHeight / viewHeight;
          context.fillStyle = "#FF0000";
          context.fillRect(20, 10, 120, (viewHeight - 20) / PixelRatio.get());
          }

        }}
      />`

What is shown on the view:
Screenshot 2024-05-01 at 18 03 29

The exported image (I removed transparency):
tmpDrawing_canvas_extract1714579338316

And what if I use scale?
context.scale(this.canvasScaleWidth, this.canvasScaleHeight);

The view:
Screenshot 2024-05-01 at 18 06 27
The exported image (I removed transparency):

tmpDrawing_canvas_extract1714579626384

Any idea how to fix? I know nothing about canvas and I was wondering what it is that you do with the matrix transformation in the source code, and if that may be the issue.
Any idea @iddan?
Thank you.

@Pingou
Copy link
Author

Pingou commented May 4, 2024

I think the issue is that in the autoScaleCanvas function the style width and height are set to be the same dimensions as the canvas internal width/height, but it shouldn't. I changed it with some other stuff and it fixed my issue, feel free to look at my fork.

@gun-ctrl
Copy link

I advise that you should set width and height after the canvas is initialized,I have encountered similar problems before

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