Gregg
Gregg

Reputation: 667

Set Canvas strokeStyle color from a CSS property?

In our Angular2 / Ionic 2 project we have a HTML Canvas element that can be drawn on. How can I set the Canvas strokeStyle property using a color provided by a CSS style?

Below is a snippet of the draw function. Is it possible to set the context.strokeStyle property to a value retrieved from CSS?

draw = function () {
            context.clearRect(0, 0, self.canvas.nativeElement.width, self.canvas.nativeElement.height);
            context.strokeStyle = "#000";
            context.lineJoin = "round";
            context.lineWidth = 5;
            for (var i = 0; i < clickX.length; i++) {
                context.beginPath();
                if (clickDrag[i] && i) {
                    context.moveTo(clickX[i - 1], clickY[i - 1]);
                } else {
                    context.moveTo(clickX[i] - 1, clickY[i]);
                }
                context.lineTo(clickX[i], clickY[i]);
                context.closePath();
                context.stroke();
            }
            self.canvasEmpty.emit(self.isCanvasEmpty());
        },

My original thought was to assign a CSS class to the canvas tag with the color property set. Then I would retrieve the value of the color property from self.canvas.nativeElement. However, no CSS styles are available when I inspect self.canvas.nativeElement using Chrome Web Inspector tools.

Upvotes: 7

Views: 3428

Answers (1)

user1693593
user1693593

Reputation:

In general, you can attach the style or class to an element which is temporarily inserted to DOM and then use getComputedStyle() for the color property to get a string which can be used with stokeStyle in 2D context.

Any should do as strokeStyle do take a CSS color:

A DOMString parsed as CSS value.

Note that color can return the value transparent which you may want to handle separately.

Example

Below is an example on how to retrieve the color value based on a class-name. The element is inserted into DOM because some browsers require it in order to calculate the CSS property values.

Change the color in the CSS class to change the color for the arc drawn in canvas.

var ctx = document.querySelector("canvas").getContext("2d");

function colorFromCSSClass(className) {
  var tmp = document.createElement("div"), color;
  tmp.style.cssText = "position:fixed;left:-100px;top:-100px;width:1px;height:1px";
  tmp.className = className;
  document.body.appendChild(tmp);  // required in some browsers
  color = getComputedStyle(tmp).getPropertyValue("color");
  document.body.removeChild(tmp);
  return color
}

// alter color in style-sheet to alter stroke color
ctx.strokeStyle = colorFromCSSClass("myStyle");
ctx.lineWidth = 5;
ctx.arc(150, 75, 70, 0, 6.28);
ctx.stroke();
/* Alter color here to alter stroke color in canvas */
.myStyle {
  color:#09f;
  }
<canvas></canvas>

Upvotes: 8

Related Questions