canvas to image
by Jesse M
HTML
<button class="add-text">add text</button><br />
<div class="wrap">
<canvas id="canvas-test" width="200" height="95"></canvas>
</div>
<br />
<button class="generate">generate image</button>
<br />
<img src="" />
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica, sans-serif;
}
.wrap {
position: relative;
}
canvas {
background: #fff;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
/*
.text {
position: absolute;
top: 10px;
left: 10px;
}
*/
JavaScript
var canvas = document.getElementById('canvas-test');
var context = canvas.getContext("2d");
var image = new Image();
image.src = "https://www.maximumgames.com/wp-content/themes/TheSource/images/esrb_rating/esrb_mature_blood_gore_voilence.jpg";
context.drawImage(image,0, 0, 200, 95);
// text
//context.fillStyle = "blue";
//context.font = "400 16px Arial";
//context.fillText('some test text', (canvas.width / 2) - 30, (canvas.height / 2) - 5);
// background
//context.globalCompositeOperation = 'destination-over';
//context.fillStyle = "#F00";
//context.fillRect(0, 0, canvas.width, canvas.height);
// set text
$('.add-text').on('click', function(e){
e.preventDefault();
var canvas2 = document.getElementById('canvas-test');
var context2 = canvas2.getContext("2d");
context2.fillStyle = "blue";
context2.font = "400 16px Arial";
context2.fillText('some test text', (canvas2.width / 2) - 30, (canvas2.height / 2) - 5);
});
// make image
$('.generate').click(function(e){
e.preventDefault();
var imgSrc = document.getElementById('canvas-test').toDataURL();
$('img').attr('src', imgSrc);
});