gpt4 book ai didi

javascript - 从 CSS 属性设置 Canvas strokeStyle 颜色?

转载 作者:太空狗 更新时间:2023-10-29 18:13:57 25 4
gpt4 key购买 nike

在我们的 Angular2/Ionic 2 元素中,我们有一个可以在其上绘制的 HTML Canvas 元素。 如何使用 CSS 样式提供的颜色设置 Canvas strokeStyle 属性?

下面是绘制函数的片段。是否可以将 context.strokeStyle 属性设置为从 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());
},

我最初的想法是将一个 CSS 类分配给具有 color 属性集的 canvas 标签。然后我将从 self.canvas.nativeElement 中检索 color 属性的值。但是,当我使用 Chrome Web 检查器工具检查 self.canvas.nativeElement 时,没有可用的 CSS 样式。

最佳答案

通常,您可以将样式或类附加到临时插入 DOM 的元素,然后使用 getComputedStyle()color 属性获取字符串可以在 2D 上下文中与 stokeStyle 一起使用。

任何应该像 strokeStyle 那样做 do take a CSS color :

A DOMString parsed as CSS value.

请注意,color 可以返回值 transparent,您可能希望单独处理该值。

例子

下面是一个关于如何根据类名检索颜色值的示例。该元素被插入到 DOM 中,因为一些浏览器需要它来计算 CSS 属性值。

更改 CSS 类中的颜色以更改在 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>

关于javascript - 从 CSS 属性设置 Canvas strokeStyle 颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40978050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com