These forums are currently read-only due to receiving more spam than actual discussion. Sorry.

It is currently Sat Dec 02, 2017 4:12 pm Advanced search

Fill Pattern

If you are stuck or have questions regarding HTML or other Web technologies, ask your questions here. No question too dumb!

Fill Pattern

Postby JayJam » Wed Aug 15, 2012 8:46 am

Hi,

I'm looking at creating a certain shape with HTML 5 canvas and filling with a pattern (image)
Code: Select all
// Init
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');


Code: Select all
var DRAW = {
   layerOne: function() {
        var ctx = canvas.getContext('2d');

        ctx.beginPath();
        ctx.moveTo(0,150);
        ctx.lineTo(652,1365);
        ctx.lineTo(1790,2030);
        ctx.lineTo(860,2940);
        ctx.lineTo(1307,3324);
        ctx.lineTo(1430,3653);
        ctx.lineTo(190,4156);
        ctx.lineTo(1660,4660);
        ctx.lineTo(596,5862);
        ctx.lineTo(723,5990);
        ctx.lineTo(50,6650);
        ctx.lineTo(1090,7380);
        ctx.lineTo(0,8350);

        var img    = new Image();
        img.src    =  'images/patternBlack.jpg';
        var pat=ctx.createPattern(img,"repeat");
        ctx.fillStyle=pat;
        ctx.fill();
   }
};


This gets called on Document.ready
Code: Select all
$(document).ready(function() {

    if (canvas.getContext){
      DRAW.layerOne();
   }
});


I am able to get the shape but can't get the pattern to fill, i'm not too sure what i'm missing here, any help in the right direction would be great,

Thankyou!
JayJam
<h6>
 
Posts: 1
Joined: Wed Aug 15, 2012 8:40 am

Re: Fill Pattern

Postby d.szlachta » Fri Sep 07, 2012 2:18 pm

Hi,

Your code works fine for me (it makes a triangle-like shape). I've changed only one thing - the image url, as I don't have your file. Maybe here's the problem? Contex 2d spec (http://www.w3.org/TR/2dcontext/#dom-con ... atepattern) says, that createPattern method throws an error, when image isn't ok, so you can change your code (DRAW) to:
Code: Select all
try {
  var pat=ctx.createPattern(img,"repeat");
} catch(e) {
  alert(e);
}


and see if you get an error message.
d.szlachta
<h6>
 
Posts: 2
Joined: Fri Sep 07, 2012 1:41 pm


Return to Help & Advice

Who is online

Users browsing this forum: No registered users and 1 guest