【问题标题】:Image filling in polygon using Raphael js or any another js使用 Raphael js 或任何其他 js 填充多边形的图像
【发布时间】:2016-02-24 05:47:11
【问题描述】:

我面临在屋顶选择的多边形内填充背景图像的问题。 我已经成功创建了多边形,现在我希望从存在的幻灯片数量中选择图像后,该图像应该填充在所选多边形中。 我正在使用 Raphael js 做同样的事情,如果可能的话,请提供任何其他 js。

以下是用于测试目的的代码:

// Creates canvas 320 × 200 at 10, 50
var paper = Raphael(10, 50, 320, 200);
//draw triangle
var t = paper.path("M0 0L250 0L100 100L 0");
// Sets the fill attribute of the circle to red (#f00)
t.attr("fill", "url('http://interlock.renoworks.com/en/data/exterior/Slate/~Interlock-01-SlateRoofing/~swatch1-400.jpg')");
// Sets the stroke attribute of the circle to white
t.attr("stroke", "#f00");

这里是演示网址:http://jsfiddle.net/hxez863d/5/

【问题讨论】:

  • 我会包含一些测试代码。
  • @Ian 我已经添加了测试代码。
  • 这对我来说似乎工作正常(即它充满了图像?)你能澄清一下你想要发生的事情不在示例中吗?

标签: javascript jquery raphael


【解决方案1】:

您可以在没有库的情况下在 HTML5 中剪辑路径。之后在画布上绘制,将东西放入剪辑区域。

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

var noise = makeNoise(300,200);
var squares = makeSquares(300, 200, 10, "#CCCCCC", "#999999");

// Draw background image.
ctx.drawImage(noise, 0, 0);


ctx.save();
//var paper = Raphael(10, 50, 320, 200);
ctx.translate(10, 50);

ctx.save();
//draw triangle
//var t = paper.path("M0 0L250 0L100 100L 0");
clipPath(ctx, [
  [0,0],
  [250, 0],
  [100, 100],
  [0, 0]
]);

// Draw with clip.
ctx.drawImage(squares, 0, 0);
ctx.fillRect(90, 70, 30, 30);
ctx.restore(); // <-- removes clip

// Draw without clip.
ctx.fillStyle = "red";
ctx.fillRect(100, 80, 30, 30);

ctx.restore(); // <-- removes translate

function clipPath(ctx, coords) {
  ctx.beginPath();
  ctx.moveTo(coords[0][0], coords[0][1]);
  for (var i = 1; i < coords.length; i++) {
    ctx.lineTo(coords[i][0], coords[i][1]);
  }
  ctx.clip();
}

function makeNoise(w, h) {
  var can = document.createElement('canvas');
  can.width = w;
  can.height = h;
  var ctx = can.getContext('2d');
  var imageData = ctx.getImageData(0, 0, w, h);
  var d = imageData.data;
  var len = d.length;
  for (var i = 0; i < len; i+=4) {
    d[i] = d[i+1] = d[i+2] = Math.floor(Math.random() * 256);
    d[i+3] = 255;
  }
  ctx.putImageData(imageData, 0, 0);
  return can;
}

function makeSquares(w, h, size, color1, color2) {
  var can = document.createElement('canvas');
  var ctx = can.getContext('2d');
  can.width = w;
  can.height = h;
  
  for (var y = 0; y < h; y+= size) {
    for (var x = 0; x < w; x += size*2) {
      ctx.fillStyle = color1;
      ctx.fillRect(x, y, size, size);
      ctx.fillStyle = color2;
      ctx.fillRect(x + size, y, size, size);
    }
    var temp = color1;
    color1 = color2;
    color2 = temp;
  }
  return can;
}
&lt;canvas id="can" width="300" height="200"&gt;&lt;/canvas&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 2012-12-17
    • 2016-07-16
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    相关资源
    最近更新 更多