21.07.2014, 10:24
|
Аспирант
|
|
Регистрация: 20.08.2013
Сообщений: 88
|
|
Рисовалка на Canvas - как добавить инструмент?
Добрый день, пробую для себя написать маленький редактор на канвасе. Не могу понять как добавить инструменты - в моем случае кроме точки, еще линию и прямоугольник. Внешний вид пока что схематичный.
Есть примеры инструментов:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#container { position: relative; }
#imageView { border: 1px solid #000; }
#imageTemp { position: absolute; top: 1px; left: 1px; }
</style>
</head>
<body>
<p><label>Drawing tool: <select id="dtool">
<option value="line">Line</option>
<option value="rect">Rectangle</option>
<option value="pencil">Pencil</option>
</select></label></p>
<div id="container">
<canvas id="imageView" width="400" height="300">
<p>Unfortunately, your browser is currently unsupported by our web
application. </p>
</canvas>
</div>
<script type="text/javascript">
if(window.addEventListener) {
window.addEventListener('load', function () {
var canvas, context, canvaso, contexto;
var tool;
var tool_default = 'line';
function init () {
canvaso = document.getElementById('imageView');
if (!canvaso) {
alert('Error: I cannot find the canvas element!');
return;
}
if (!canvaso.getContext) {
alert('Error: no canvas.getContext!');
return;
}
contexto = canvaso.getContext('2d');
if (!contexto) {
alert('Error: failed to getContext!');
return;
}
var container = canvaso.parentNode;
canvas = document.createElement('canvas');
if (!canvas) {
alert('Error: I cannot create a new canvas element!');
return;
}
canvas.id = 'imageTemp';
canvas.width = canvaso.width;
canvas.height = canvaso.height;
container.appendChild(canvas);
context = canvas.getContext('2d');
var tool_select = document.getElementById('dtool');
if (!tool_select) {
alert('Error: failed to get the dtool element!');
return;
}
tool_select.addEventListener('change', ev_tool_change, false);
if (tools[tool_default]) {
tool = new tools[tool_default]();
tool_select.value = tool_default;
}
canvas.addEventListener('mousedown', ev_canvas, false);
canvas.addEventListener('mousemove', ev_canvas, false);
canvas.addEventListener('mouseup', ev_canvas, false);
}
function ev_canvas (ev) {
if (ev.layerX || ev.layerX == 0) { // Firefox
ev._x = ev.layerX;
ev._y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
ev._x = ev.offsetX;
ev._y = ev.offsetY;
}
var func = tool[ev.type];
if (func) {
func(ev);
}
}
function ev_tool_change (ev) {
if (tools[this.value]) {
tool = new tools[this.value]();
}
}
function img_update () {
contexto.drawImage(canvas, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
}
var tools = {};
tools.pencil = function () {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
context.beginPath();
context.moveTo(ev._x, ev._y);
tool.started = true;
};
this.mousemove = function (ev) {
if (tool.started) {
context.lineTo(ev._x, ev._y);
context.stroke();
}
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
};
tools.rect = function () {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
tool.started = true;
tool.x0 = ev._x;
tool.y0 = ev._y;
};
this.mousemove = function (ev) {
if (!tool.started) {
return;
}
var x = Math.min(ev._x, tool.x0),
y = Math.min(ev._y, tool.y0),
w = Math.abs(ev._x - tool.x0),
h = Math.abs(ev._y - tool.y0);
context.clearRect(0, 0, canvas.width, canvas.height);
if (!w || !h) {
return;
}
context.strokeRect(x, y, w, h);
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
};
tools.line = function () {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
tool.started = true;
tool.x0 = ev._x;
tool.y0 = ev._y;
};
this.mousemove = function (ev) {
if (!tool.started) {
return;
}
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(tool.x0, tool.y0);
context.lineTo(ev._x, ev._y);
context.stroke();
context.closePath();
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
};
init();
}, false); }
</script>
<body>
</html>
Последний раз редактировалось piraids, 21.07.2014 в 10:26.
|
|
21.07.2014, 10:24
|
Аспирант
|
|
Регистрация: 20.08.2013
Сообщений: 88
|
|
А это мой пробник так сказать, в который хочу собственно добавить инструменты:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<title>Untitled</title>
<style>
#test
{
background: #FFFFFF;
border: solid 1px #333;
cursor: pointer;
width: 100%;
height: 400px;
margin: 10px 0px;
}
#preview
{
border:1px #000 solid;
height:40px;
width:40px;
}
</style>
</head>
<body>
<ul class="demoToolList">
<li>Clear the canvas: <button id="clearCanvas" type="button">Clear</button></li>
<li>
<span class="highlight">Choose a tool: </span>
<button id="choosePencilTools" type="button">Pencil</button>
<button id="chooseRectTools" type="button">Rectangle</button>
<button id="chooseLineTools" type="button">Line</button>
</li>
</ul>
<div id="panel">
<div id="preview"></div>
</div>
<div id="test"></div>
<script type="text/javascript">
var canvas,
canvasColor,
contextColor,
context,
canvasDiv = document.getElementById('test'),
panelsDiv = document.getElementById('panel'),
canvasWidth = canvasDiv.offsetWidth,
canvasHeight = canvasDiv.offsetHeight,
defaultColor = '#000000'
curColor = defaultColor,
clickColor = new Array(),
clickTool = new Array(),
curTool = "pencil";
canvasColor = document.createElement('canvas');
canvasColor.setAttribute('width', '500');
canvasColor.setAttribute('height', '50');
canvasColor.setAttribute('id', 'color');
panelsDiv.appendChild(canvasColor);
if(typeof G_vmlCanvasManager != 'undefined') {
canvasColor = G_vmlCanvasManager.initElement(canvasColor);
}
contextColor = canvasColor.getContext("2d");
drawGradients(contextColor);
canvas = document.createElement('canvas');
canvas.setAttribute('width', canvasWidth);
canvas.setAttribute('height', canvasHeight);
canvas.setAttribute('id', 'canvas1');
canvasDiv.appendChild(canvas);
if(typeof G_vmlCanvasManager != 'undefined') {
canvas = G_vmlCanvasManager.initElement(canvas);
}
context = canvas.getContext("2d");
clearColors();
$('#color').mousemove(function(e) { // обработчик движения мыши
var canvasOffset = $(canvasColor).offset();
var canvasX = Math.floor(e.pageX - canvasOffset.left);
var canvasY = Math.floor(e.pageY - canvasOffset.top);
var imageData = contextColor.getImageData(canvasX, canvasY, 1, 1);
var pixel = imageData.data;
var R = pixel[0];
var G = pixel[1];
var B = pixel[2];
var hex = rgbToHex(R,G,B);
var pixelColor = '#'+hex;
$('#preview').css('backgroundColor', pixelColor);
});
$('#color').click(function(e) { // обработчик щелчка мыши
var canvasOffset = $(canvasColor).offset();
var canvasX = Math.floor(e.pageX - canvasOffset.left);
var canvasY = Math.floor(e.pageY - canvasOffset.top);
var imageData = contextColor.getImageData(canvasX, canvasY, 1, 1);
var pixel = imageData.data;
var R = pixel[0];
var G = pixel[1];
var B = pixel[2];
var hex = rgbToHex(R,G,B);
curColor = '#'+hex;
$('#preview').css('backgroundColor', curColor);
});
$('#color').mouseleave(function(){
$('#preview').css('backgroundColor', curColor);
});
function drawGradients() {
var grad = contextColor.createLinearGradient(20, 0, canvasColor.width - 20, 0);
grad.addColorStop(0, 'black');
grad.addColorStop(1 / 8, 'white');
grad.addColorStop(2 / 8, 'red');
grad.addColorStop(3 / 8, 'orange');
grad.addColorStop(4 / 8, 'yellow');
grad.addColorStop(5 / 8, 'green')
grad.addColorStop(6 / 8, 'aqua');
grad.addColorStop(7 / 8, 'blue');
grad.addColorStop(1, 'purple');
contextColor.fillStyle=grad;
contextColor.fillRect(0, 0, canvasColor.width, canvasColor.height);
grad = contextColor.createLinearGradient(0, 0, 0, canvasColor.height);
grad.addColorStop(0, "rgba(255, 255, 255, 1)");
grad.addColorStop(0.5, "rgba(255, 255, 255, 0)");
grad.addColorStop(0.5, "rgba(0, 0, 0, 0)");
grad.addColorStop(1, "rgba(0, 0, 0, 1)");
contextColor.fillStyle = grad;
contextColor.fillRect(0, 0, canvasColor.width, canvasColor.height);
}
function rgbToHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
function toHex(n) {
n = parseInt(n,10);
if (isNaN(n)) return "00";
n = Math.max(0,Math.min(n,255));return "0123456789ABCDEF".charAt((n-n%16)/16) + "0123456789ABCDEF".charAt(n%16);
}
$('#canvas1').mousedown(function(e){
var parentOffset = $(this).parent().offset();
var mouseX = e.pageX - parentOffset.left;
var mouseY = e.pageY - parentOffset.top;
paint = true;
addClick(mouseX, mouseY);
redraw();
});
$('#canvas1').mousemove(function(e){
if(paint){
var parentOffset = $(this).parent().offset();
addClick(e.pageX - parentOffset.left, e.pageY - parentOffset.top, true);
redraw();
}
});
$('#canvas1').mouseup(function(e){
paint = false;
});
$('#canvas1').mouseleave(function(e){
paint = false;
});
var clickX = new Array(),
clickY = new Array(),
clickDrag = new Array(),
paint;
function addClick(x, y, dragging)
{
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
clickColor.push(curColor); //добавление цветов
}
//buttons
$('#clearCanvas').mousedown(function(e)
{
clickX = new Array();
clickY = new Array();
clickDrag = new Array();
clickColor = new Array();
clearColors();
clearCanvas();
});
$('#choosePencilTools').mousedown(function(e){
curTool = "pencil";
});
$('#chooseRectTools').mousedown(function(e){
curTool = "rect";
});
$('#chooseLineTools').mousedown(function(e){
curTool = "line";
});
//buttons end
function clearColors()
{
curColor = defaultColor;
$('#preview').css('backgroundColor', curColor);
}
function clearCanvas()
{
context.clearRect(0, 0, canvas.width, canvas.height);
}
function redraw(){
context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas
context.lineJoin = "round";
context.lineWidth = 5;
for(var i=0; i < clickX.length; i++) {
context.beginPath();
if(clickDrag[i] && i){
context.moveTo(clickX[i-1], clickY[i-1]);
}else{
context.moveTo(clickX[i]-1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.strokeStyle = clickColor[i]; //выбор цвета
context.stroke();
}
}
</script>
</body>
</html>
|
|
|
|