JSFiddle - React, Tailwind, and code Playground
by ghostoy
HTML
<!-- Canvas with fallbacks -->
<canvas id="canvas1" width="400" height="400" style="border: 1px solid black;">
<p>Sorry your browser don't support canvas</p>
</canvas>
<div>
<label for="x_axis">X:</label> <input type="number" value="0" id="x_axis"/>
<label for="y_axis">Y:</label> <input type="number" value="0" id="y_axis"/>
<label for="rotate">Rotate:</label> <input type="number" value="0" id="rotate" step="0.1"/>
<label for="color">Color:</label> <input type="color" value="rgba(255, 0, 0, 0.5)" id="color"/>
<p>
<button onclick="clearCanvas()">Clear</button>
<button onclick="drawImage('http://www.google.com/intl/en_com/images/srpr/logo3w.png')">Draw Image</button>
<button onclick="drawRect()">Draw Rect</button>
</p>
</div>
JavaScript
function getCanvas() {
return document.getElementById('canvas1');
}
function clearCanvas() {
var canvas = getCanvas(),
context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
}
function getTranslate() {
return {
x: document.getElementById('x_axis').valueAsNumber,
y: document.getElementById('y_axis').valueAsNumber
};
}
function getRotate() {
return document.getElementById('rotate').valueAsNumber * Math.PI / 180;
}
function getColor() {
return document.getElementById('color').value;
}
function drawImage(url) {
var img = new Image();
img.src = url;
img.addEventListener('load', function(){
var canvas = getCanvas(), // get the canvas
context = canvas.getContext('2d'), // get 2d context
tran = getTranslate(),
rotate = getRotate();
context.save(); // save current canvas state (fillStyle/transform matrix etc.)
context.translate(tran.x, tran.y);
context.rotate(rotate);
context.drawImage(img, 0, 0); // draw image at (x,y)
context.restore(); // restore previous canvas state
}, false);
}
function drawRect() {
var canvas = getCanvas(), // get canvas
context = canvas.getContext('2d'), // get 2d context
tran = getTranslate(),
rotate = getRotate(),
color = getColor();
context.save();
context.translate(tran.x, tran.y);
context.rotate(rotate);
context.fillStyle = color;
context.fillRect(0, 0, 150, 100); // fill the rect
context.restore();
}