代码之家  ›  专栏  ›  技术社区  ›  Igor Zinov'yev

有没有办法在画布路径上平铺背景图像?

  •  2
  • Igor Zinov'yev  · 技术社区  · 15 年前

    例如,我在一个页面中有一个画布,上面有某种路径。它是由javascript创建的,方法如下:

    var context = $('#some_canvas').getContext('2d');
    context.beginPath();
    context.lineWidth = 5;
    context.strokeStyle = '#000000';
    context.moveTo(0, 0);
    context.lineTo(100, 100);
    context.stroke();
    

    有没有办法让这个命令后面出现的路径有一些平铺的背景图像?

    1 回复  |  直到 15 年前
        1
  •  4
  •   Ionuț G. Stan    15 年前

    我相信你在找 createPattern() 方法:

    var pattern = new Image;
    pattern.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAARCAIAAABbzbuTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAZtJREFUeNqMUs+rAVEUvjNG2MhClOUsppSEjbWFpOwtMIv5B2ZhZqkkZKkpe+XPYKtsbSxsZIGaQpgi4r3Pu5p3eV45dW/nnPt959zzg5RKpU6n8/WxkHq9LghCs9n8lICjKAohpFwuf0LgcCzLSqfTo9FIVVVd10He7XbX6/V8Pu/3e47jcB+Px0AgkEqlCOXNZjNJkgB1/wg+6XA4ACXPomkasXM1Gg3yj4AZi8WAHgwGgu1dLpcvOKRKJBLZbDaTyYDgdDrvXjtDLpd7yT6dTv8WzdNnaPP53A6Mezgc+v3+N/+jvO12GwwGqQfFYJRQksnker1+MwfIZDLxeDwA+Xy+xWIBT6VSgYk+Hg4HlvAoerVaodNQ8vl8KBSCUqvVAG2326g4EolsNhuYGNQjQ6/XAwh9GI/HbDxZltn/o2OPDBgctaPRKIsQRZEqWJxisXg3aaRCoQBvv99nw59Op3A4DH+1Wu12u09FYwh4w/6wBGwUOhuPx6FfLpfb7fZbtGEYpmnyPM/+x+v1tlotl8sFHdtFnd8CDACAg6Y2weEZQQAAAABJRU5ErkJggg==";
    pattern.onload = function () {
        var context = $('#some_canvas').getContext('2d');
        context.beginPath();
        context.lineWidth = 16;
        context.strokeStyle = context.createPattern(pattern, 'repeat');
        context.moveTo(0, 0);
        context.lineTo(150, 150);
        context.stroke();
    };