Drawing bezier curves
by Milan Gladiš
HTML
<canvas id="draw"></canvas>
CSS
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
background-color: #fff;
}
body {
/* padding: 10px; */
}
#draw {
background-color: #eee;
}
JavaScript
// Initialize
var canvas = document.querySelector('#draw');
var ctx = canvas.getContext('2d');
// Variables
var mouse = {x: 0, y: 0};
var last_mouse = {x: 0, y: 0};
// Size of the canvas
var ratio = window.devicePixelRatio || 1;
var sketch = document.querySelector('body');
var sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'))*2;
canvas.height = parseInt(sketch_style.getPropertyValue('height'))*2;
canvas.style.width = canvas.width/2 + "px";
canvas.style.height = canvas.height/2 + "px";
ctx.scale(ratio, ratio);
// Visual settings
ctx.lineWidth = 2;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = '#999';
// Mouse Down
canvas.addEventListener('mousedown', function() {
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
canvas.addEventListener('mousemove', onPaint, false);
console.log('mousedown on ' + mouse.x + " * " + mouse.y);
}, false);
// Mouse Move
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
});
// Mouse Up
canvas.addEventListener('mouseup', function() {
console.log('mouseup');
//ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear
canvas.removeEventListener('mousemove', onPaint, false);
}, false);
function onPaint() {
console.log('onPaint');
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear
ctx.moveTo(mouse.x, mouse.y);
ctx.beginPath();
ctx.arc(last_mouse.x,last_mouse.y,6,0,2*Math.PI);
// ctx.lineTo(mouse.x, mouse.y);
//context.moveTo(200, 200);
centerx = (200 + mouse.x)/2;
centery = (200 + mouse.y)/2;
console.log('lastm.x ' + 200);
console.log('lastm.y ' + 200);
console.log('modx.x ' + centerx);
// console.log('mody ' + mody);
console.log('mouse.x ' + mouse.x);
console.log('mouse.y ' + mouse.y);
console.log('—');
//ctx.moveTo(last_mouse.x, last_mouse.y);
// ctx.moveTo(200, 200);
/* ...