react-native-canvas icon indicating copy to clipboard operation
react-native-canvas copied to clipboard

Setting width/height of canvas doesn't work

Open Pingou opened this issue 1 year ago • 2 comments

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 avatar May 01 '24 16:05 Pingou

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.

Pingou avatar May 04 '24 16:05 Pingou

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

gun-ctrl avatar Jun 26 '24 05:06 gun-ctrl