首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >画布重复矩形并不是唯一的

画布重复矩形并不是唯一的
EN

Stack Overflow用户
提问于 2017-03-29 18:50:25
回答 1查看 32关注 0票数 1

我正在尝试编写一个函数,允许使用不同的文本值创建重复的矩形,以及一个更改框颜色的标志。我很难得到每个函数调用的文本,以及显示在每个框上的正确颜色。最后,我得到了一系列电话中的最后一个框,这是唯一一个带有可见文本的框。我做错了什么?

代码语言:javascript
复制
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的一些调用,并在下面的小提琴中看到结果。

JSFiddle

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-29 19:08:54

要使绘图方法仅适用于在一个函数调用中所做的事情,请在函数中添加以下一行:

代码语言:javascript
复制
ctx.beginPath();

代码语言:javascript
复制
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);
代码语言:javascript
复制
<canvas id="canvas"></canvas>

如果没有这一行,fillstroke方法适用于到目前为止绘制的所有内容。使用beginPath,您可以巩固以前所做的工作,并从一个新的“节”开始。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43101793

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档