iddan / react-native-canvas

A Canvas component for React Native
MIT License
995 stars 172 forks source link

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

Open Pingou opened 7 months ago

Pingou commented 7 months ago

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 commented 6 months ago

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 commented 5 months ago

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