Practice Set, Week 4, Drawing on the Canvas

by Jordan Marechal

HTML

<b>Practice Set 14.2: Circle your favorite dog!</b>
<p>In this practice problem, you will use CanvasRenderingContext2D methods to draw a circle on the image of the dogs. See the Javascript comments for guidance.</p>
<div>Original image:
    <br/>
    <img src="https://courses.dce.harvard.edu/~cscie3/examples/week14/proxy.php" width="200" id="orig" crossorigin="anonymous" />
</div>
<div>Canvas
    <br/>
    <canvas id="c1" width="200" height="134"></canvas>
</div>

CSS

canvas {
    border:1px solid blue;
}
#output {
    border: 1px solid gray;
}
div {
   float:left;
}
p {
clear: both;
}

JavaScript

//window.onload = function (){// get the canvas and context objects
var canvas = document.getElementById("c1");
var ctx = canvas.getContext('2d');

// get the image object
var img = $("#orig");



// Draw the image on the canvas.
ctx.drawImage(img[0], 0, 0, canvas.width, canvas.height);

// We can keep drawing with this 'ctx' object.  Let's set some styles 
ctx.strokeStyle = "red";
ctx.lineWidth = "2";

function Circle(x, y, r, color){
this.x = x;
this.y = y;
this.r = r;
this.color = color;

}
var c = new Circle(100, 100, 50, 'rgba(60, 60, 0, 1)');
c.draw();
Circle.protoype.draw = function() {
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0, Math.PI*2, false);
ctx.fillStyle = this.color;
ctx.fill();
ctx.strokeStyle = '#bbb';

}



//  Now, we're going to draw a circle on the image. Remember from the example in 
// video 14.4 how to draw a circle, or check the MDN docs:
//  https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/arc.
//  In steps: 
//    call beginPath() to start the drawing path
//    call arc() to create the circle
//    call stroke() to draw it

//  You will write these three lines of code to circle your favorite dog (of
//    the two here). If you don't have a favorite dog, pick at random. :-)
//    You'll need the coordinates of the center of the circle you'll draw.
//    Here are each dog's coordinates: 
//   Baxter (Hound on the left)  60,60
//   Ripley (Dobie on the right) 125,35