HMTL Canvas - Paint + RXjs
RxJS 5 throttleTime
by black strings
HTML
<script src="https://npmcdn.com/@reactivex/[email protected]/dist/global/Rx.umd.js"></script>
CSS
.colorbox{
display: inline-block;
border: thin solid #ccc;
width:20px;
height:20px;
padding:0;
margin:0;
}
.blue{background-color: blue;}
.red{background-color: red;}
.green{background-color: green;}
.grey{background-color: grey;}
.black{background-color: black;}
.white{background-color: white;}
JavaScript
//emit value every 1 second
//const source = Rx.Observable.interval(1000);
/*
throttle for five seconds
last value emitted before throttle ends will be emitted from source
*/
/*
const example = source
.throttleTime(5000);
//output: 0...6...12
const subscribe = example.subscribe(val => console.log(val));
*/
var isDown = false;
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var width;
var height;
function draw(evt){
if(isDown){
var x = evt.offsetX;
var y = evt.offsetY;
ctx.lineTo(x,y);
ctx.stroke();
}
}
function onDown(evt){
isDown = true;
ctx.beginPath(); // will start fresh and not remember previous strokes
ctx.moveTo(evt.offsetX,evt.offsetY);
ctx.lineJoin = ctx.lineCap = 'round'; // smooth edge
//ctx.shadowBlur = 10;
//ctx.shadowColor = 'rgb(0, 0, 0)';
ctx.lineWidth = 5;
}
function onUp(evt){
isDown = false;
//ctx.closePath();
}
function clearCanvas(evt){
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "#e3c8a1";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function createUI(){
var div = document.createElement('div');
document.body.appendChild(div);
var btn = document.createElement('button');
btn.innerHTML = 'clear';
div.appendChild(btn);
btn.addEventListener('click', (evt) => {
clearCanvas(evt);
});
var colors = [
{name:'black', code: "#000000"},
{name:'grey', code: "#cccccc"},
{name:'white', code: "#ffffff"},
{name:'blue', code: "#0000ff"},
{name:'red', code: "#ff0000"},
{name:'green', code: "#00ff00"}
]
for(var i=0; i<colors.length; i++){
var btn = document.createElement('div');
btn.classList.add('colorbox', colors[i].name);
div.appendChild(btn);
btn.colr = colors[i].code;
btn.addEventListener('click', function(evt){
ctx.strokeStyle = evt.currentTarget.colr;
});
}
}
createUI();
var moveEvt = Rx.Observable.fromEvent(document, 'mousemove');
// either or works
/* var moveObs =...