mattdesl / canvas-sketch

[beta] A framework for making generative artwork in JavaScript and the browser.
MIT License
5.01k stars 393 forks source link

Getting "context.createLinearGradient is not a function" error when trying to set a canvas fill #106

Closed rjgrazioli closed 3 years ago

rjgrazioli commented 4 years ago

Trying to set a gradient background for the canvas—referencing the docs and while trying to use context.createLinearGradient I get a "context.createLinearGradient is not a function" error.;

Note: I get an error when using context.fillRect too. What am I doing wrong?


global.THREE = require("three");
const canvasSketch = require("canvas-sketch");

const settings = {
  animate: true,
  context: "webgl",
  scaleToView: true
};

var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;

const sketch = ({ context }) => {

  // Renderer
  // -------------------------------------------------------
  const renderer = new THREE.WebGLRenderer({
    canvas: context.canvas,
    alpha: true,
  });

  // Gradient foreground
  const fill = context.createLinearGradient(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
  fill.addColorStop(0, 'cyan');
  fill.addColorStop(1, 'orange');

  // Fill rectangle
  context.fillStyle = fill;```
mattdesl commented 4 years ago

WebGL (ie ThreeJS and 3D) is a very different and incompatible interface compared to Canvas2D (which you are using there for your gradient). You can’t mix the two APIs unfortunately! An HTML5 canvas is either created with a 2D context (the default in canvas-sketch), or with a WebGL context (much more complex!).

I’d stick with 2D canvas API if you’re just starting off.