(function(doc) {
function $(a) {
switch (a.slice(0, 1)) {
case "#":
return doc.getElementById(a.slice(1));
case ".":
return [].slice.call(doc.getElementsByClassName(a.slice(1)));
}
}
function save(e) {
var cnv = $(e.target.getAttribute('data-canvas')),
lnx = $('#savelink');
lnx.href = cnv.toDataURL();
lnx.download = e.target.getAttribute('data-res') +
'_ ' + cnv.width + 'x' +
cnv.height + '.png';
lnx.click();
}
function lowRes(cnv, ctx) {
var img = new Image;
img.addEventListener('load', function() {
ctx.clearRect(0, 0, cnv.width, cnv.height);
ctx.drawImage(this, 0, 0);
});
img.src = cnv.toDataURL('image/jpeg', 0.64);
};
function draw(id, wh, lw, res) {
var cnv = $(id),
ctx = cnv.getContext('2d'),
xy = wh / 2,
fc = 8,
shrink = (xy * 0.9) / fc,
flag = !1;
cnv.width = wh,
cnv.height = wh,
ctx.lineWidth = lw;
ctx.fillStyle = '#eee';
ctx.fillRect(0,0,cnv.width,cnv.height);
ctx.beginPath();
ctx.moveTo(0, xy);
ctx.lineTo(cnv.width, xy);
while (--fc) {
ctx.arc(xy, xy, shrink * fc, 0, Math.PI, flag);
flag = !flag;
}
ctx.stroke();
ctx.fillStyle = '#777';
ctx.font = Math.round(cnv.height * 0.025) + 'px serif';
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
ctx.beginPath();
ctx.fillText(
('lineWidth = ' + lw +
', width/height = ' + wh + 'px, ' +
(res ? 'low-res' : 'hi-res')),
Math.round(cnv.width * 0.9),
Math.round(cnv.height * 0.96)
);
res && lowRes(cnv, ctx);
}
doc.addEventListener('DOMContentLoaded', function() {
[
['#c1', 500, 1, !1],
['#c2', 1500, 3, !1],
['#c3', 500, 1, !0],
['#c4', 1500, 3, !0]
].forEach(function(n) {
draw.apply(null, n);
});
$('.save').forEach(function(n) {
n.addEventListener('click', save, !1);
});
}, false);
}(document));
.ch {
position:relative;
width:500px;
height:500px;
border:1px solid #999;
margin:2rem auto;
}
.ch canvas {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
display:block;
}
.ch .save {
position:absolute;
top:2%;
left:2%;
color:#aaa;
font-size:2rem;
font-weight:600;
cursor:pointer;
display:inline-block;
transition:color 333ms;
}
.ch .save:hover {
color:#000;
}
<div class="ch">
<canvas id="c1"></canvas>
<div class="save" title=" Save Image " data-canvas="#c1" data-res="hi">⇩</div>
</div>
<div class="ch">
<canvas id="c2"></canvas>
<div class="save" title=" Save Image " data-canvas="#c2" data-res="hi">⇩</div>
</div>
<div class="ch">
<canvas id="c3"></canvas>
<div class="save" title=" Save Image " data-canvas="#c3" data-res="lo">⇩</div>
</div>
<div class="ch">
<canvas id="c4"></canvas>
<div class="save" title=" Save Image " data-canvas="#c4" data-res="lo">⇩</div>
</div>
<a id="savelink" href="" download="" target="_blank"></a>