I'm trying to create a HTML5 canvas with a simple gradient in LWC. However, it's all black. The code I'm trying is almost completely copied from W3C (except it's adjusted for LWC).


    <div class="chart" lwc:dom="manual"></div>


import { LightningElement } from 'lwc';

export default class CanvasTest extends LightningElement {
    rendered = false;

    renderedCallback() {
      if (this.rendered) {
      this.rendered = true;

      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      // Create gradient
      const grd = ctx.createLinearGradient(0, 0, 200, 0);
      grd.addColorStop(0, 'red');
      grd.addColorStop(1, 'white');

      // Fill with gradient
      ctx.fillStyle = grd;
      ctx.fillRect(10, 10, 150, 80);

I've tried a few non-gradient canvas functionalities and everything seems ok, but I can't get gradients to work at all. How can I fix this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.