1

How can you fill a shape created in javascript with an image?

I am using a shape I created with javascript and am right now filling it with a color. How can I replace that and fill it with an image/gif of my choice?

function shape(x,y) {

        ctx.fillStyle = "#9dd4ff";
        ctx.beginPath();
        ctx.moveTo(232,213)
        ctx.lineTo(315,198);
        ctx.lineTo(x,y);
        ctx.closePath();
        ctx.fill();
}
4

2 に答える 2

1

パスをマスクとして使用することで、この問題を解決できます。

ここにコードがあります

// Create an image element 
var img = document.createElement('IMG');   
// When the image is loaded, draw it 
img.onload = function () {   
    // Save the state, so we can undo the clipping 
    ctx.save();   
    // Create a shape, of some sort 
    ctx.beginPath(); 
    ctx.moveTo(10, 10);
    ctx.lineTo(100, 30); 
    ctx.lineTo(180, 10); 
    ctx.lineTo(200, 60);
    ctx.arcTo(180, 70, 120, 0, 10); 
    ctx.lineTo(200, 180); 
    ctx.lineTo(100, 150);
    ctx.lineTo(70, 180);
    ctx.lineTo(20, 130);
    ctx.lineTo(50, 70);
    ctx.closePath();
    // Clip to the current path 
    ctx.clip();   
    ctx.drawImage(img, 0, 0);   
    // Undo the clipping 
    ctx.restore(); 
}   
// Specify the src to load the image 
img.src = "https://www.google.com/images/srpr/logo3w.png";
于 2012-12-13T06:40:06.890 に答える
0

これを試して:

var thumbImg = document.createElement('img');

thumbImg.src = 'path_to_image';



function shape(x,y) {

        ctx.fillStyle = "#9dd4ff";
        ctx.beginPath();
        ctx.moveTo(232,213)
        ctx.lineTo(315,198);
        ctx.lineTo(x,y);


        ctx.drawImage(thumbImg, 0, 0, 50, 50);

        ctx.closePath();
        ctx.fill();
}

- 編集 -

削除するctx.fillStyle ="#9dd4ff"

画像のパスに言及する必要があるため。

于 2012-12-13T06:30:58.700 に答える