LoginSignup
7
4

More than 5 years have passed since last update.

PixiJSでグラデーションを描きたい

Last updated at Posted at 2018-12-08

PixiJSは2DのWebGLを使いたいときにとても便利なライブラリですが、グラデーションの描画が機能としては用意されていないので、Canvasと組み合わせて実装する必要があります。

といっても、そんなに大げさなことではなく、Canvas要素を用意してグラデーションを設定して、それをもとにSpriteを生成するだけなので、わりとシンプルです。

const createGradient = (width, height, colorFrom, colorTo) => {
  const canvas = document.createElement('canvas')  
  const ctx = canvas.getContext('2d')
  const gradient = ctx.createLinearGradient(0, 0, width, 0)

  canvas.setAttribute('width', width)
  canvas.setAttribute('height', height)

  gradient.addColorStop(0, colorFrom)
  gradient.addColorStop(1, colorTo)

  ctx.fillStyle = gradient
  ctx.fillRect(0, 0, width, height)

  return PIXI.Sprite.from(canvas)
}

const app = new PIXI.Application({
  width: 500,
  height: 300
})

const gradient = createGradient(500, 300, '#acb6e5', '#86fde8')

app.stage.addChild(gradient)

document.getElementById('app').appendChild(app.view)

See the Pen Create Gradient With PixiJS by noplan1989 (@noplan1989) on CodePen.

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4