画布图案不重复

时间:2017-03-09 05:15:03

标签: javascript jquery html css canvas

我正在使用以下javascript创建Canvas模式:

//$('#canvas1').height($(document).height());
//console.log($('#canvas1').width($(document).width()));

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');

// set up a pattern
var pattern = document.createElement('canvas');
pattern.width = 80;
pattern.height = 80;
var pctx = pattern.getContext('2d');

pctx.beginPath();
pctx.lineWidth = "3";
pctx.strokeStyle = "red";
pctx.rect(74, 74, 3, 3);  
pctx.stroke();

var pattern = ctx.createPattern(pattern, "repeat");
ctx.rect(0,0,800,800);
ctx.fillStyle = pattern;
ctx.fill();

即使将ctx.rect值定义为800,结果模式似乎也不会重复。画布如下:

<canvas id="canvas1"style="position:absolute;left:0;top:0;"></canvas>

如何在当前页面的高度和宽度上重复它。我知道我可以使用jQuery来设置高度和宽度,我测试了它,但模式仍然没有重复。我哪里错了?

2 个答案:

答案 0 :(得分:1)

好吧,我猜你对.rect()的参数感到困惑。它应该是pctx.rect(3, 3, 74, 74)

&#13;
&#13;
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');

// set up a pattern
var pattern = document.createElement('canvas');
pattern.width = 80;
pattern.height = 80;
var pctx = pattern.getContext('2d');

pctx.beginPath();
pctx.lineWidth = "3";
pctx.strokeStyle = "red";
pctx.rect(3, 3, 74, 74);
pctx.stroke();

var _pattern = ctx.createPattern(pattern, "repeat");
ctx.rect(0, 0, can.width, can.height);
ctx.fillStyle = _pattern;
ctx.fill();
&#13;
<canvas id="canvas1" width="320" height="320" style="border: 1px solid black; position: absolute; left: 0; top: 0;"></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我不确定这是否是您问题的根源,但是当您更改宽度时,您应该写pattern.style.width = "80px"; 这同样适用于身高 如果能解决您的问题,请告诉我