javascript - 在 Canvas 上使用 createPattern()

标签 javascript html canvas design-patterns repeat

我正在尝试获取重复的 Canvas 图案。可悲的是,我能找到的所有例子都重复了一张图片。所以我尝试了这个:

function init() {
var canvas = document.getElementById("bg");
var ctx = canvas.getContext("2d");

//creating a new canvas  
var canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 400;
var img = canvas.getContext("2d");

draw(img);
var objPattern = ctx.createPattern(img, "repeat");
ctx.fillStyle = objPattern;
ctx.fillRect(0, 0, document.body.clientHeight, document.body.clientWidth);
}

function draw(img) {
  //img.save();
  img.beginPath();
  img.moveTo(0.0, 40.0);
  img.lineTo(26.9, 36.0);
  img.bezierCurveTo(31.7, 36.0, 36.0, 32.1, 36.0, 27.3);
  img.lineTo(40.0, 0.0);
  img.lineTo(11.8, 3.0);
  img.bezierCurveTo(7.0, 3.0, 3.0, 6.9, 3.0, 11.7);
  img.lineTo(0.0, 40.0);
  img.closePath();
  img.fillStyle = "rgb(188, 222, 178)";
  img.fill();
  img.lineWidth = 0.8;
  img.strokeStyle = "rgb(0, 156, 86)";
  img.lineJoin = "miter";
  img.miterLimit = 4.0;
  img.stroke();
  //img.restore();
}

并将其包含到 html 文件中,如下所示:

<body onload="init()">
<canvas id="bg" width=100%; height=100%;></canvas>
…

我真的不想使用循环来使用偏移量“手动”重复模式,因为我觉得(并希望)应该有一种更简单的方法。绘图代码中的save和restore在一些教程和例子中用到了,但对我来说没有任何意义,所以我把它们注释掉了。

最佳答案

任何在 Canvas 中拍摄图像的东西也可以采用 Canvas 元素。

这里是您绘制图案的示例,如果您需要更细粒度的控制,还可以使用自定义图案函数:

<!-- HTML -->
<canvas id="canvas1" width="500" height="500"></canvas>
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');



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

pctx.beginPath();
pctx.moveTo(0.0, 40.0);
pctx.lineTo(26.9, 36.0);
pctx.bezierCurveTo(31.7, 36.0, 36.0, 32.1, 36.0, 27.3);
pctx.lineTo(40.0, 0.0);
pctx.lineTo(11.8, 3.0);
pctx.bezierCurveTo(7.0, 3.0, 3.0, 6.9, 3.0, 11.7);
pctx.lineTo(0.0, 40.0);
pctx.closePath();
pctx.fillStyle = "rgb(188, 222, 178)";
pctx.fill();
pctx.lineWidth = 0.8;
pctx.strokeStyle = "rgb(0, 156, 86)";
pctx.lineJoin = "miter";
pctx.miterLimit = 4.0;
pctx.stroke();

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

这里要注意的关键是创建的 Canvas 只有 40x40 像素,刚好足以容纳图案。

http://jsfiddle.net/UxDVR/7/

关于javascript - 在 Canvas 上使用 createPattern(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5530799/

相关文章:

javascript - 如果使用 jquery 在该行中进行了任何修改,如何更改突出显示的当前表行

javascript - 使用三元运算符如何检查值来自哪个 $stateParams?

javascript - 正则表达式从文件中提取路径

javascript - HTML+JavaScript 日历

javascript - 在不支持 vw 或 vh 属性的旧移动浏览器中会发生什么情况?

html - 制作特色图片背景图片

javascript - 矩形正在翻转和旋转。我只是想让它绕一圈旋转

javascript - Ember.js - 如何过滤模型?

javascript - Canvas 到 png 不工作 fabricjs

javascript - 函数对象无法将图像从 Canvas 绘制到图像