Skip to content

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

Open
@Pingou

Description

@Pingou

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions