I'm new to canvas, I was learning from MDN's Canvas tutorial's color gradient part, and when I wanted to run the context.createConicGradient browser throws error:
Uncaught TypeError: context.createConicGradient is not a function
I even copied the same code from the tutorial, but it throws this error anyway. I thought that this method was removed or deprecated from JS, but I didn't find anything reliable.
Here is the code from the tutorial:
var conicGrad1 = ctx.createConicGradient(2, 62, 75);
conicGrad1.addColorStop(0, '#A7D30C');
conicGrad1.addColorStop(1, '#fff');
The method createConicGradient() is experimental and not yet available in most browsers.
Check below for browser compatibility:
https://caniuse.com/mdn-api_canvasrenderingcontext2d_createconicgradient
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createConicGradient#browser_compatibility
If you want to experiment, you can open in Firefox:
about:config
Then enable the property below:
canvas.createConicGradient.enabled
After that, your code will work.
Here is one helpful polyfill you can use: https://github.com/parksben/create-conical-gradient
import 'create-conical-gradient'; // If you use the npm package.
const canvas = document.getElementById('my-canvas');
const ctx = canvas.getContext('2d');
const gradient = ctx.createConicalGradient(240, 135, -Math.PI, Math.PI);
gradient.addColorStop(0, '#f00');
gradient.addColorStop(0.2, '#00f');
gradient.addColorStop(0.4, '#0ff');
gradient.addColorStop(0.6, '#f0f');
gradient.addColorStop(0.8, '#ff0');
gradient.addColorStop(1, '#f00');
ctx.fillStyle = gradient.pattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With