如何用图像填充javascript中创建的形状?

时间:2012-12-13 06:03:27

标签: javascript image html5 canvas fill

如何使用图像填充javascript中创建的形状?

我正在使用我用javascript创建的形状,现在正在用颜色填充它。如何替换它并用我选择的图像/ gif填充它?

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();
}

2 个答案:

答案 0 :(得分:1)

您可以将路径用作MASK

来解决此问题

这是代码

// 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";

答案 1 :(得分: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"

你需要提一下图像的路径。

相关问题