JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<p>This is the line image</p>
<img src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png">
<p>The line image rotated at center of canvas</p>
<canvas id="canvas" width=300 height=300></canvas>

CSS

body {
    background-color: ivory;
    padding:10px;
}
canvas {
    border:1px solid red;
}

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// This is an image loader 
// When render() is called, all your images are fully loaded
var imgURLs = [
    "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
    "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
    "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png"];
var imgs = [];
var imgCount = 0;

pre_load();

function pre_load() {

    for (var i = 0; i < imgURLs.length; i++) {

        var img = new Image();
        imgs.push(img);
        img.onload = function () {

            if (++imgCount >= imgs.length) {
                // images are now fully loaded
                render();
            }

        }
        img.src = imgURLs[i];
    }
}


// draw the rotated lines on the canvas
function render() {

    var x = canvas.width / 2;
    var y = canvas.height / 2;

    drawImageAtAngle(imgs[0], x, y, -45);
    drawImageAtAngle(imgs[2], x, y, 45);
    drawImageAtAngle(imgs[1], x, y, 0);
}


function drawImageAtAngle(image, X, Y, degrees) {
    var radians = degrees * Math.PI / 180;
    var halfWidth = image.width / 2;
    var halfHeight = image.height / 2;
    ctx.beginPath();
    ctx.save();
    ctx.translate(X, Y);
    ctx.rotate(radians);
    ctx.drawImage(image, -halfWidth, -halfHeight);
    ctx.restore();
}