我正面临着在屋顶顶部选择的多边形内填充背景图像的问题。 我已经成功创建了多边形,现在我想要的是,只要从存在的幻灯片数量中选择图像,该图像就应该在所选多边形内填充。 我正在使用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/
答案 0 :(得分:0)
您可以在没有库的情况下剪辑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;
}
<canvas id="can" width="300" height="200"></canvas>