canvaskineticjs

Continuous hatch line needed in canvas with repeated pattern


I am trying to build a hatch pattern using a combination of canvas and kinetic and I am having issues trying to get a continuous line.

This jsfiddle shows what I have so far, but because my repeat pattern is a sqaure the corners are affecting the line, I have tried using the lineJoin and lineCap properties, but cannot seem to get the desired result.

The main code in question is this:

var hatchPattern = document.getElementById("canvas")
var context = hatchPattern.getContext('2d');
context.strokeStyle = "#FF0000";
context.beginPath();
context.moveTo(0, 20);
context.lineTo(20, 0);
context.lineWidth = 5;
context.stroke();
context.closePath();

Can anyone help?

UPDATE:

I have created another jsfiddle which although not perfect, will probably do for me, still not sure why there is a slight gap though!


Solution

  • To create diagonal lines covering your canvas, you can create a pattern like this:

    You must fill the top-left & bottom-right corner with a triangle. When repeated as in a pattern, these triangles will fill in the beveled corners caused by your center line coming to a point at top-right & bottom-left

    enter image description here

    Then createPattern(yourPattern,"repeat") will pattern-fill the canvas like this:

    enter image description here

    Here's example code and a Demo showing thinner lines:

    enter image description here

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    
    var p = document.createElement("canvas")
    p.width=32;
    p.height=16;
    var pctx=p.getContext('2d');
    
    var x0=36;
    var x1=-4;
    var y0=-2;
    var y1=18;
    var offset=32;
    
    pctx.strokeStyle = "#FF0000";
    pctx.lineWidth=2;
    pctx.beginPath();
    pctx.moveTo(x0,y0);
    pctx.lineTo(x1,y1);
    pctx.moveTo(x0-offset,y0);
    pctx.lineTo(x1-offset,y1);
    pctx.moveTo(x0+offset,y0);
    pctx.lineTo(x1+offset,y1);
    pctx.stroke();
    
    ctx.fillStyle=ctx.createPattern(p,'repeat');
    ctx.fillRect(0,0,canvas.width,canvas.height);
    #canvas{border:1px solid red;}
    <canvas id="canvas" width=300 height=300></canvas>