Creating a superelipse with canvas
Today a colleague asked a group of front-end developers how he would create a superelipse. His current solution was to use a svg mask to remove all non essential visual information. This solution however had a setback, because we used a mask to shield the edges we had no real transparency. Thus we were unable to effectively use it on more graphic backgrounds. I however thought it should be able to use canvas to provide the solution. The code below is my solution.
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var image = canvas.getContext('2d');
var width = canvas.width;
var height= canvas.height;
var img = document.createElement('IMG');
var shape = {
beginPath : function(node) {
image.beginPath();
image.moveTo(
node.x,
node.y
);
},
createCurve : function(curve, node) {
image.quadraticCurveTo(
curve.x,
curve.y,
node.x,
node.y
);
},
node : {
top_left : {
x : ((width/100)*20),
y : ((height/100)*5)
},
top_right : {
x : ((width/100)*80),
y : ((height/100)*5)
},
right_top :{
x : ((width/100)*95),
y : ((height/100)*20)
},
right_bottom :{
x : ((width/100)*95),
y : ((height/100)*80)
},
bottom_right : {
x : ((width/100)*80),
y : ((height/100)*95)
},
bottom_left : {
x : ((width/100)*20),
y : ((height/100)*95)
},
left_bottom : {
x : ((width/100)*5),
y : ((height/100)*80)
},
left_top : {
x : ((width/100)*5),
y : ((height/100)*20)
}
},
curve : {
top : {
x : ((width/100)*50),
y : 0
},
top_right : {
x : ((width/100)*92.5),
y : ((height/100)* 7.5)
},
right : {
x : width,
y : ((height/100)* 50)
},
bottom_right : {
x : ((width/100)*92.5),
y : ((height/100)*92.5)
},
bottom : {
x : ((width/100)*50),
y : height
},
bottom_left : {
x : ((width/100)*7.5),
y : ((height/100)*92.5)
},
left : {
x : 0,
y : ((height/100)*50)
},
top_left : {
x : ((width/100)*7.5),
y : ((height/100)*7.5)
}
}
}
img.onload = function() {
shape.beginPath(shape.node.top_left)
shape.createCurve(shape.curve.top, shape.node.top_right);
shape.createCurve(shape.curve.top_right, shape.node.right_top);
shape.createCurve(shape.curve.right, shape.node.right_bottom);
shape.createCurve(shape.curve.bottom_right, shape.node.bottom_right);
shape.createCurve(shape.curve.bottom, shape.node.bottom_left);
shape.createCurve(shape.curve.bottom_left, shape.node.left_bottom);
shape.createCurve(shape.curve.left, shape.node.left_top);
shape.createCurve(shape.curve.top_left, shape.node.top_left);
image.closePath();
image.clip();
image.drawImage(img, 0, 0, width, height);
image.restore();
}
img.src = "http://goo.gl/pC8iIF";
</script>
So should you ever be faced with the requirement of creating specific shape for images please remember that canvas is a good way to do so.