我正在尝试编写一个函数,允许使用不同的文本值创建重复的矩形,以及一个更改框颜色的标志。我很难得到每个函数调用的文本,以及显示在每个框上的正确颜色。最后,我得到了一系列电话中的最后一个框,这是唯一一个带有可见文本的框。我做错了什么?
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
this.buildBox = function(xpos, ypos, width, height, text, colorFlag) {
ctx.font = '12px Arial';
ctx.strokeStyle = 'black';
ctx.fillStyle = colorFlag === true ? '#ff6666' : '#fff';
ctx.rect(xpos, ypos, width, height);
ctx.fill();
ctx.stroke();
function textFill(text, offset) {
}
if(text !== null && text !== undefined) {
ctx.strokeText(text, xpos + 10, ypos + 20);
}
}
// test data
this.buildBox(84,10,64,44, 888, true);
this.buildBox(84,64,64,44, 999, false);
this.buildBox(84,118,64,44, 777, true);要进行测试,请尝试注释掉对buildBox的一些调用,并在下面的小提琴中看到结果。
发布于 2017-03-29 19:08:54
要使绘图方法仅适用于在一个函数调用中所做的事情,请在函数中添加以下一行:
ctx.beginPath();
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
this.buildBox = function(xpos, ypos, width, height, text, colorFlag) {
ctx.beginPath();
ctx.font = '12px Arial';
ctx.strokeStyle = 'black';
ctx.fillStyle = colorFlag === true ? '#ff6666' : '#fff';
ctx.rect(xpos, ypos, width, height);
ctx.fill();
ctx.stroke();
function textFill(text, offset) {
}
if(text !== null && text !== undefined) {
ctx.strokeText(text, xpos + 10, ypos + 20);
}
}
// test data
this.buildBox(84,10,64,44, 888, true);
this.buildBox(84,64,64,44, 999, false);
this.buildBox(84,118,64,44, 777, true);<canvas id="canvas"></canvas>
如果没有这一行,fill和stroke方法适用于到目前为止绘制的所有内容。使用beginPath,您可以巩固以前所做的工作,并从一个新的“节”开始。
https://stackoverflow.com/questions/43101793
复制相似问题