如何解决实时预览HTML5 Canvas背景和颜色
如何通过实时预览更改HTML5画布的背景和文本颜色?
我在[JSFiddle] [1]上提供的代码仅在关闭调色板后才更改背景和文本颜色。我还希望画布上的文本具有可变的font-family和font-size。我在任何地方都找不到解决方案。
如果代码无法运行,请通过创建html文件解决问题。
请查看此[image] [2]了解更多信息。
任何建议和帮助将不胜感激。
[1]: https://jsfiddle.net/p0z1vau3/
[2]: https://i.stack.imgur.com/ZpETT.png
[3]: Source: https://codepen.io/stefan0uh/pen/QzJVxa
解决方法
在您的代码中,将eventListener更改为:
color.addEventListener("input",render);
bgcolor.addEventListener("input",render);
您可以在此处阅读有关颜色选择器的更多信息:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/color
,如果您需要如何编码字体大小和字体系列的更改,请使用以下代码。它还包括对两个问题的回答。以此替换您的JavaScript代码。
const color = document.getElementById("color");
const canvas = document.getElementById("canvas");
const style = document.getElementById("font-family");
const size = document.getElementById("font-size");
const ctx = canvas.getContext("2d");
// onload
window.onload = () => {
render();
};
// Eventlistner
color.addEventListener("input",render);
bgcolor.addEventListener("input",render);
style.addEventListener("change",render);
size.addEventListener("change",render);
// text positions
function render() {
drawBackground();
drawText("top",canvas.height - 48,size.value,style.value);
drawText("bottom",canvas.height - 18);
}
// Need live preview for background color
function drawBackground() {
ctx.fillStyle = bgcolor.value;
ctx.fillRect(0,canvas.height - 80,canvas.width + 10,150);
ctx.restore();
}
function drawText(text,position,fontSize,fontStyle) {
ctx.fillStyle = "#ffffff";
ctx.font = fontSize+"px "+ fontStyle; // Need variable font-family & size
// Need live preview for color
var top = [{
text: ` Text`,font: `lighter ${ctx.font}`,fillStyle: color.value}];
var bottom = [{
text: `......Text`,fillStyle: color.value }];
fillMixedText(ctx,text === "top" ? top : bottom,20,position);//text positioning
}
// fillStyle
function fillMixedText(ctx,args,x,y) {
let defaultFillStyle = ctx.fillStyle;
let defaultFont = ctx.font;
args.forEach(({ text,fillStyle,font }) => {
ctx.fillStyle = fillStyle || defaultFillStyle;
ctx.font = font || defaultFont;
ctx.fillText(text,y);
x += ctx.measureText(text).width;
});
ctx.restore();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。