Skip to content

Instantly share code, notes, and snippets.

@jcasabona
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcasabona/35bbf0a8fe2a543dc27e to your computer and use it in GitHub Desktop.
Save jcasabona/35bbf0a8fe2a543dc27e to your computer and use it in GitHub Desktop.

Define Canvas:

Put this in the HTML section:

<canvas id="cherries" width="600" height="400"></canvas>

and this in the JS section:

var canvas = document.getElementById('cherries');
var context = canvas.getContext('2d');

Draw first Cherry:

in JS section:

context.beginPath();
var centerX1 = canvas.width / 3;
var centerY1 = canvas.height / 2;
var radius = 30; 

This defines our starting point for both the cherry and the stem.

Since we want the stem to show 'behind' the cherry, we draw that first, using a bezierCurve. This will start at our center, then draw a link to the midpoints we define. Here, we have 3 points (x1, y1, x2, y2, x3, y3)

context.moveTo(centerX1, centerY1);
context.bezierCurveTo(280, 30, 320, 40, 340, 50);
context.lineWidth = 1;

context.strokeStyle = '#006600';
context.stroke();

Now we draw the cherry by drawing a red circle with a black border:

context.beginPath();
context.arc(centerX1, centerY1, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'red';
context.fill();
context.lineWidth= 1;
context.strokeStyle= '#000000';
context.stroke();

Draw 2nd Cherry:

Now time for the 2nd cherry. We want that to just touch the first one, while making it clear there are 2 objects.

var centerX2 = canvas.width / 2.4;
var centerY2 = canvas.height / 1.8;
var radius = 30;

Once again, we draw the stem first, follow the same path as above so they end up at the same x3, y3.

context.beginPath();
context.moveTo(centerX2, centerY2);
context.bezierCurveTo(280, 30, 320, 40, 340, 50);
context.lineWidth = 1;

// line color
context.strokeStyle = '#006600';
context.stroke();

And the 2nd cherry:

context.beginPath();
context.arc(centerX2, centerY2, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'red';
context.fill();

context.lineWidth = 1;
context.strokeStyle = '#000000';
context.stroke();

Now let's give it a text label:

context.font = '40pt helvetica';
context.fillStyle = 'red';
context.fillText('Cherries!', 150, 340);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment