Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to use CSS colors with HTML5 canvas?

Currently I use the javascript code like below:

var gradient = ctx.createLinearGradient(0, 0, 30, 0);
gradient.addColorStop(0.00, 'green');
gradient.addColorStop(0.01, 'white');
gradient.addColorStop(1.00, 'white');
...
ctx.shadowColor = 'rgba(0, 0, 0, 0.9)';
...
ctx.fillStyle = 'rgba(0, 128, 0, ' + alpha + ')';
ctx.fillStyle = 'rgba(255, 255, 255, ' + alpha + ')';

Is there any way to move these definitions to CSS?

like image 697
LA_ Avatar asked Oct 26 '25 04:10

LA_


1 Answers

Indirectly, yes...

You can fetch the CSS style applied to any element on your page using:

var elementStyle=window.getComputedStyle(anyElement, null);

Then you can query the text color of that element using:

var elementColor=elementStyle.getPropertyCSSValue('color');

enter image description here

Here's example code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var sourceElement=document.getElementById("source");
var color=window.getComputedStyle(sourceElement,null).getPropertyValue("color");
var bk=window.getComputedStyle(sourceElement,null).getPropertyValue("background-color");

ctx.fillStyle=bk;
ctx.fillRect(0,0,cw,ch);

ctx.font='36px times';
ctx.fillStyle=color;
ctx.fillText('from #source',30,100);
body{ background-color:white; padding:10px; }
#canvas{border:1px solid red;}
#source{color:maroon;background-color:ivory;
  width:100px;height:75px;border:1px solid blue;padding:10px;}
<div id=source>I'm #source</div>
<canvas id="canvas" width=350 height=200></canvas>
like image 85
markE Avatar answered Oct 27 '25 19:10

markE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!