NativeScript / canvas

Apache License 2.0
88 stars 18 forks source link

Canvas globalCompositeOperation = source-in not working with gradients on Android #51

Closed darkyelox closed 8 months ago

darkyelox commented 3 years ago

Hi, always here testing this super awesome library (for me a game changer in NS like RootLayout) now I have this issue when using gradients and trying to mask for create an icon that crops and has the color of the gradient. What I'm trying to do is to create a Font Awesome icon with a gradient pattern so I tried as follows:

const canvasContext = canvas.getContext('2d') as unknown as CanvasRenderingContext2D

const { width, height } = getViewConstraints(canvas as any)

const itemsWidth = width / this.items.length

canvasContext.clearRect(0, 0, width, height)
canvasContext.setTransform(1, 0, 0, 1, 0, 0)

canvasContext.save()

this.items.forEach((item, index) => {
  const leftOffset = itemsWidth * index

  const gradient = canvasContext.createLinearGradient(leftOffset, 0, leftOffset + itemsWidth, height)
  gradient.addColorStop(0, 'red')
  gradient.addColorStop(1, 'yellow')
  gradient.addColorStop(2, 'green')

  const font = Font.default.withFontFamily('fa-regular-400')
  const imageSource = ImageSource.fromResourceSync('splash_image')
  const iconImageSource = ImageSource.fromFontIconCodeSync(String.fromCharCode(0xf0c0), font, new Color('white'))

  canvasContext.fillStyle = 'black'
  canvasContext.drawImage(iconImageSource as any, 50,0, 150, 150)
  // canvasContext.fillRect(50, 0, 150, 150)

  canvasContext.globalCompositeOperation = 'source-in'

  canvasContext.fillStyle = gradient
  canvasContext.fillRect(leftOffset, 0, itemsWidth, height)
  // canvasContext.drawImage(imageSource as any, 0,0, itemsWidth, height)

})

canvasContext.restore()

The icon remains white and no gradient is shown, also I tried using a simple rectangle instead of the icon and the gradient is not shown at all, I sometimes gets a solid color into my rectangle. The solution for now is to use an image as gradient instead of a gradient.

My environment:

@nativescript/canvas: 1.0.0-alpha.2 @nativescript/core: 8.1.0-alpha.7 @nativescript/android: 8.0.0 cli: 8.0.2

triniwiz commented 3 years ago

Thanks again for testing 🙂 , I'll check it out

triniwiz commented 8 months ago

Fixed in v2