I am building a HTML5 canvas image editor. After uploading an image in to the canvas i need to Dragg and resize it over the canvas.
I managed to upload an image and make it draggable on the canvas. But i need to make it resizable also along the canvas. Thanks in advance.
var Img = new Image();
Img.src = file;
Img.onload = function () {
context.drawImage(Img, 50, 0, 200, 200);
}
mouseMove = function (event){
if (down)
{
context.clearRect(0,0,800,500);
context.translate(0, -50);
context.drawImage(Img, (event.clientX - offsetX),
(event.clientY - offsetY), 200, 200);
context.translate(0, 50);
}
}
mouseUp = function () {
down = false;
}
mouseDown = function () {
down = true;
}
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mouseup', mouseUp, false);
canvas.addEventListener('mousemove',mouseMove, false);
I tried with kinetics js but it is not suitable with canvas.
Here's example code to allow you to drag and resize an image using Canvas.
Resizing
How to resize an image with 4 draggable anchors
Draw a draggable anchor on each corner of an image.
If the user mousedown’s one if the anchors, start dragging that anchor.
In the mousemove handler, resize the image using the dragging anchor’s position(Note below).
As the last act in mousemove, redraw the resized image and 4 new anchors.
On mouseup, stop the anchor’s drag.
Note on the math used to resize the image:
The resized width is the difference between the mouseX position and the opposite corner’s X.
The resized height is the difference between the mouseY position and the opposite corner’s Y.
Dragging
How to drag an image
If the user mousedown’s inside the image, save the mouses starting XY to begin dragging.
In the mousemove handler, move the image by the current mouseXY minus the startingXY.
Also in mousemove, reset the startingXY to the current mouseXY in preparation for continued dragging.
On mouseup, stop the image’s drag.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/LAS8L/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:10px;}
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var startX;
var startY;
var isDown=false;
var pi2=Math.PI*2;
var resizerRadius=8;
var rr=resizerRadius*resizerRadius;
var draggingResizer={x:0,y:0};
var imageX=50;
var imageY=50;
var imageWidth,imageHeight,imageRight,imageBottom;
var draggingImage=false;
var startX;
var startY;
var img=new Image();
img.onload=function(){
imageWidth=img.width;
imageHeight=img.height;
imageRight=imageX+imageWidth;
imageBottom=imageY+imageHeight
draw(true,false);
}
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/facesSmall.png";
function draw(withAnchors,withBorders){
// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
// draw the image
ctx.drawImage(img,0,0,img.width,img.height,imageX,imageY,imageWidth,imageHeight);
// optionally draw the draggable anchors
if(withAnchors){
drawDragAnchor(imageX,imageY);
drawDragAnchor(imageRight,imageY);
drawDragAnchor(imageRight,imageBottom);
drawDragAnchor(imageX,imageBottom);
}
// optionally draw the connecting anchor lines
if(withBorders){
ctx.beginPath();
ctx.moveTo(imageX,imageY);
ctx.lineTo(imageRight,imageY);
ctx.lineTo(imageRight,imageBottom);
ctx.lineTo(imageX,imageBottom);
ctx.closePath();
ctx.stroke();
}
}
function drawDragAnchor(x,y){
ctx.beginPath();
ctx.arc(x,y,resizerRadius,0,pi2,false);
ctx.closePath();
ctx.fill();
}
function anchorHitTest(x,y){
var dx,dy;
// top-left
dx=x-imageX;
dy=y-imageY;
if(dx*dx+dy*dy<=rr){ return(0); }
// top-right
dx=x-imageRight;
dy=y-imageY;
if(dx*dx+dy*dy<=rr){ return(1); }
// bottom-right
dx=x-imageRight;
dy=y-imageBottom;
if(dx*dx+dy*dy<=rr){ return(2); }
// bottom-left
dx=x-imageX;
dy=y-imageBottom;
if(dx*dx+dy*dy<=rr){ return(3); }
return(-1);
}
function hitImage(x,y){
return(x>imageX && x<imageX+imageWidth && y>imageY && y<imageY+imageHeight);
}
function handleMouseDown(e){
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
draggingResizer=anchorHitTest(startX,startY);
draggingImage= draggingResizer<0 && hitImage(startX,startY);
}
function handleMouseUp(e){
draggingResizer=-1;
draggingImage=false;
draw(true,false);
}
function handleMouseOut(e){
handleMouseUp(e);
}
function handleMouseMove(e){
if(draggingResizer>-1){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// resize the image
switch(draggingResizer){
case 0: //top-left
imageX=mouseX;
imageWidth=imageRight-mouseX;
imageY=mouseY;
imageHeight=imageBottom-mouseY;
break;
case 1: //top-right
imageY=mouseY;
imageWidth=mouseX-imageX;
imageHeight=imageBottom-mouseY;
break;
case 2: //bottom-right
imageWidth=mouseX-imageX;
imageHeight=mouseY-imageY;
break;
case 3: //bottom-left
imageX=mouseX;
imageWidth=imageRight-mouseX;
imageHeight=mouseY-imageY;
break;
}
// enforce minimum dimensions of 25x25
if(imageWidth<25){imageWidth=25;}
if(imageHeight<25){imageHeight=25;}
// set the image right and bottom
imageRight=imageX+imageWidth;
imageBottom=imageY+imageHeight;
// redraw the image with resizing anchors
draw(true,true);
}else if(draggingImage){
imageClick=false;
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// move the image by the amount of the latest drag
var dx=mouseX-startX;
var dy=mouseY-startY;
imageX+=dx;
imageY+=dy;
imageRight+=dx;
imageBottom+=dy;
// reset the startXY for next time
startX=mouseX;
startY=mouseY;
// redraw the image with border
draw(false,true);
}
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Resize the image using the 4 draggable corner anchors</p>
<p>You can also drag the image</p>
<canvas id="canvas" width=350 height=350></canvas>
</body>
</html>
Related
Hello I'm trying to create a brush size slider for my Canvas drawing app, would anyone be able to assist in how to go about this?? A few of the approaches I have found weren't compatible with my Jquery library that I have running my app.
thank you :)
Your question is a bit brief on details :-O
Here's how to use an input-type-range to change context.lineWidth.
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
var isDown=false;
var startX,startY;
ctx.lineCap='round';
var linewidth=5;
ctx.lineWidth=linewidth;
$myslider=$('#myslider');
$myslider.attr({min:1,max:25}).val(linewidth);
$myslider.on('input change',function(){
linewidth=ctx.lineWidth=parseInt($(this).val());
});
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUpOut(e);});
$("#canvas").mouseout(function(e){handleMouseUpOut(e);});
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
isDown=true;
}
function handleMouseUpOut(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// Put your mouseup stuff here
isDown=false;
}
function handleMouseMove(e){
if(!isDown){return;}
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
ctx.beginPath();
ctx.moveTo(startX,startY);
ctx.lineTo(mouseX,mouseY);
ctx.stroke();
startX=mouseX;
startY=mouseY;
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Drag mouse to draw variable width line.</h4>
Line Width:  <input id=myslider type=range><br>
<canvas id="canvas" width=300 height=300></canvas>
Easy:
Create an input element of type range:
<input type=range min=1 max=100 id=brushSize>
Read its value and apply to lineWidth of the context:
$("#brushSize").on("input", function(e) {
ctx.lineWidth = $(this).val()
});
$("#brushSize").on("input", function(e) {
var v = $(this).val(); // brush size value, example usage:
//ctx.lineWidth = v; // context line-width
$("#val").html($(this).val()); // textual repr.
$("#val").width(v).height(v); // brush size rep.
});
#val {
display:inline-block;
border-radius:50%;
background:#000;
color:#f00;
width:50px;
height:50px;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=range min=1 max=100 id=brushSize> <span id=val>50</span>
I draw a polygon with the following code:
var canvas = document.getElementById("polyCanvas");
var c2 = canvas.getContext("2d");
var coords = '';
c2.clearRect(0, 0, 2000, 2000);
$("fdel").remove();
$("#eliminar" + todelete).remove();
c2.beginPath();
var first = true;
var points = 1;
var done = false;
$("#vertexcontainer .vertex").each(function() {
var position = $(this).position();
var x = 2+position.left;
var y = 2+position.top;
if (!done){
if (first) {
c2.moveTo(x, y);
first = false;
} else {
c2.lineTo(x, y);
}
}
if(points > cpoints){
done = true;
}
points = points + 1;
coords = coords + x + ',' + y + ' ';
});
$('#coordinates').val(coords);;
c2.closePath();
c2.lineWidth = 2;
c2.strokeStyle = '#ff0000';
c2.stroke();
c2.fillStyle = "rgb(0, 100, 200)";
c2.fill();
It runs smoothly, but i'd like to be able to drag the polygon around, or to use mouse events with it. Is that possible?
My naive attempt to do c2.hover(function..., and c2.addeventlistener... have not been successful.
You cannot actually move any drawings you've made on the canvas.
But...you can create the illusion that something is moving.
You create the illusion of movement by repeatedly erasing the canvas and redrawing the shapes in their new positions.
To drag a shape you need to listen to 4 mouse events.
In mousedown: Check if the mouse is over the shape, and, if yes, set a flag indicating a drag has begun. To check if the mouse is over the shape, you can use canvas context's isPointInPath method which tests if an [x,y] point is inside the most recently drawn path.
In mousemove: If the dragging flag is set (indicating a drag is in process), change the position of the selected text by the distance the user has dragged and redraw the shape in its new position
In mouseup or in mouseout: The drag is over so clear the dragging flag.
Here's a example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
var isDown=false;
var startX,startY;
var poly={
x:0,
y:0,
points:[{x:50,y:50},{x:75,y:25},{x:100,y:50},{x:75,y:125},{x:50,y:50}],
}
ctx.fillStyle='skyblue';
ctx.strokeStyle='gray';
ctx.lineWidth=3;
draw();
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
function draw(){
ctx.clearRect(0,0,cw,ch);
define();
ctx.fill();
ctx.stroke()
}
function define(){
ctx.beginPath();
ctx.moveTo(poly.points[0].x+poly.x,poly.points[0].y+poly.y);
for(var i=0;i<poly.points.length;i++){
ctx.lineTo(poly.points[i].x+poly.x,poly.points[i].y+poly.y);
}
ctx.closePath();
}
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
define();
if(ctx.isPointInPath(startX,startY)){
isDown=true;
}
}
function handleMouseUp(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mouseup stuff here
isDown=false;
}
function handleMouseOut(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mouseOut stuff here
isDown=false;
}
function handleMouseMove(e){
if(!isDown){return;}
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousemove stuff here
var dx=mouseX-startX;
var dy=mouseY-startY;
startX=mouseX;
startY=mouseY;
poly.x+=dx;
poly.y+=dy;
draw();
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Drag the polygon</h4>
<canvas id="canvas" width=300 height=300></canvas>
I am trying to pan the canvas when the user presses the mouse and moves it but it doesn't seem to be working for some reason I cannot see. Any ideas?
canvas.addEventListener('mousedown', onMouseDown, false);
function onMouseDown(event){
var mousePos = new Vector(event.clientX, event.clientY);
mousedown = true;
}
canvas.addEventListener('mouseup', onMouseUp, false);
function onMouseUp(event){
mousedown = false;
}
canvas.addEventListener('mousemove', onMouseMove, false);
function onMouseMove(event){
mousePos = new Vector(event.clientX, event.clientY);
if(onMouseDown){
var difference = mousePos.subtract(previousMousePosition);
pan.add(difference);
}
previousMousePosition = mousePos;
}
pan = new Vector(0, 0);
I am also getting an error saying that Vector is not defined and also one for mousePos.subtract. This is my vector.js:
var Vector = (function () {
function Vector(pX, pY) {
this.setX(pX);
this.setY(pY);
};
Vector.prototype.getX = function() {
return this.mX;
};
Vector.prototype.setX = function (pX) {
this.mX = pX;
};
Vector.prototype.getY = function() {
return this.mY;
};
Vector.prototype.setY = function(pY) {
this.mY = pY;
};
return Vector;
})();
You can pan the canvas content using the translate transformation.
context.translate(x,y) will move the canvas origin horizontally by x pixels and vertically by y pixels.
So to "pan right" by 5 pixels you can context.translate(-5,0).
The nice thing about using transformations is that you don't have to alter your existing drawing code -- translate will automatically "shift" all your drawings in the specified directions.
[ Addition: show how to get net-panning from users mouse drags ]
function log(){console.log.apply(console,arguments);}
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
var isDown=false;
var startX,startY;
var netPanningX=0;
var netPanningY=0;
var $results=$('#results');
for(var x=0;x<100;x++){ ctx.fillText(x,x*20+netPanningX,ch/2); }
for(var y=-50;y<50;y++){ ctx.fillText(y,cw/2,y*20+netPanningY); }
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
isDown=true;
}
function handleMouseUp(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mouseup stuff here
isDown=false;
}
function handleMouseOut(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mouseOut stuff here
isDown=false;
}
function handleMouseMove(e){
if(!isDown){return;}
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// dx & dy are the distance the mouse has moved since
// the last mousemove event
var dx=mouseX-startX;
var dy=mouseY-startY;
startX=mouseX;
startY=mouseY;
// accumulate the net panning done
netPanningX+=dx;
netPanningY+=dy;
$results.text('Net change in panning: x:'+netPanningX+', y:'+netPanningY);
ctx.clearRect(0,0,cw,ch);
for(var x=-50;x<50;x++){ ctx.fillText(x,x*20+netPanningX,ch/2); }
for(var y=-50;y<50;y++){ ctx.fillText(y,cw/2,y*20+netPanningY); }
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4 id=results>Drag the mouse to see net panning in x,y directions</h4>
<canvas id="canvas" width=300 height=300></canvas>
I want to make a responsive canvas using size in percentage and once user will resize the window the canvas adjust relatively.
I am able to scale the canvas by using below code but the only problem is as i scale the window size the mouse drawing disappear.
<style>
body{margin:0px;padding:0px;background:#a9a9a9;}
#main{
display:block;
width:80%;
padding:50px 10%;
height:300px;
}
canvas{display:block;background:#fff;}
</style>
</head>
<body>
<div id="main" role="main">
<canvas id="paint" width="100" height="100">
< !-- Provide fallback -->
</canvas>
</div>
<script>
var c = document.getElementById('paint');
var ctx = c.getContext('2d');
var x = null;
var y;
c.onmousedown = function(e){
x = e.pageX - c.offsetLeft;
y = e.pageY - c.offsetTop;
ctx.beginPath();
ctx.moveTo(x,y);
}
c.onmouseup = function(e){
x=null;
}
c.onmousemove = function(e){
if(x==null) return;
x = e.pageX - c.offsetLeft;
y = e.pageY - c.offsetTop;
ctx.lineTo(x,y);
ctx.stroke();
}
$(document).ready( function(){
//Get the canvas &
var c = $('#paint');
var container = $(c).parent();
//Run function when browser resizes
$(window).resize( respondCanvas );
function respondCanvas(){
c.attr('width', $(container).width() ); //max width
c.attr('height', $(container).height() ); //max height
//Call a function to redraw other content (texts, images etc)
}
//Initial call
respondCanvas();
});
</script>
Thanks.
Dealing with contents when resizing a canvas
If you resize the canvas, the drawn content is always erased. That's how canvas behaves.
You can either redraw the content after resizing or you can save the content as image data and restore after resizing (see canvas.toDataURL).
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/V6SVz/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:10px; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// draw some content
ctx.lineWidth=3;
ctx.fillStyle="blue";
ctx.strokeStyle="red";
ctx.rect(50,50,100,50);
ctx.fill();
ctx.stroke();
ctx.font="14px Verdana";
ctx.fillStyle="white";
ctx.fillText("Scale Me",65,75);
function saveResizeAndRedisplay(scaleFactor){
// save the canvas content as imageURL
var data=canvas.toDataURL();
// resize the canvas
canvas.width*=scaleFactor;
canvas.height*=scaleFactor;
// scale and redraw the canvas content
var img=new Image();
img.onload=function(){
ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);
}
img.src=data;
}
$("#resizer").click(function(){ saveResizeAndRedisplay(1.5); });
}); // end $(function(){});
</script>
</head>
<body>
<button id="resizer">Click to resize the canvas</button><br/>
<canvas id="canvas" width=200 height=150></canvas>
</body>
</html>
c.attr('width', $(container).width() ); //max width
c.attr('height', $(container).height() ); //max height
the above code is equivalent to clearRect which is used to clear the canvas .so you cannot adjust the width and height if you want to retain what was drawn previously.
as a solution you can create a new canvas with required width and draw the content of previous canvas using drawImage(c) c is the canvas object .then you have to delete the canvas
I also had the same issue that your are facing in mu application, and after reading about it i came to this conclusion that the behavior of the canvas element is such that it clears itself after re-sizing, the only fix for this is to add a listener for the window re-size event and redraw the canvas when the event if fired.
$(window).resize(function(e) {
// function to redraw on the canvas
});
$(document).ready(function(e){
var c = $('#example'); // getting the canvas element
var ct = c.get(0).getContext('2d');
var container = $(c).parent();
$(window).resize( respondCanvas ); //handling the canvas resize
function respondCanvas(){
// makign the canvas fill its container
c.attr('width', $(container).width() ); //max width
c.attr('height', ($(container).height() -20 )); //max height
}
respondCanvas();
make_image('images/india.png',1,1);
}
Hope it helps.
Source
I've created a jQuery plugin that handles HTML5 canvas resizing. It was built to bridge the gap between mobile and desktop users. It is still a WIP but it is extensible, and has some basic drawing functions built in.
http://trsanders.github.io/responsive-sketchpad/
below is the code what I was trying to do:
<head>
<style>
#main {
display:block;
width:80%;
height:300px;
background:#e0e0e0;
}
canvas {
display:block;
background:#fff;
border:1px solid red;
}
</style>
<script>
$(function(){
var container=document.getElementById("main");
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// draw some content
//alert(canvas.width);
var w=$(container).width();
var h=$(container).height();
$(window).resize( saveResizeAndRedisplay );
function saveResizeAndRedisplay(){
// save the canvas content as imageURL
var data=canvas.toDataURL();
// resize the canvas
canvas.width = $(container).width();
canvas.height = $(container).height();
//alert($(container).width());
// scale and redraw the canvas content
var img=new Image();
img.onload=function(){
ctx.drawImage(img,0,0,img.width,img.height);
}
img.src=data;
}
saveResizeAndRedisplay();
});
</script>
</head>
<body>
<div id="main" role="main">
<canvas id="canvas" width=200 height=150></canvas>
</div>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = null;
var y;
canvas.onmousedown = function(e){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
ctx.beginPath();
ctx.moveTo(x,y);
}
canvas.onmouseup = function(e){
x=null;
}
canvas.onmousemove = function(e){
if(x==null) return;
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
ctx.lineTo(x,y);
ctx.stroke();
}
</script>
</body>
I use this method:
var context = document.getElementById('paint').getContext('2d');
var canvas = context.canvas;
function responsive(width){
var p = width / canvas.width;
canvas.width *= p;
canvas.height *= p;
var scaleFactor = context.scaleFactor || 1;
context.scale(p * scaleFactor, p * scaleFactor);
context.scaleFactor = p * scaleFactor;
}
var mq = window.matchMedia("(min-width: 735px)");
mq.addListener(applyChanges);
applyChanges();
function applyChanges(){
if(!mq)
responsive(350);
else
responsive(735);
}
I had the same problem. My solution is using CSS3's property zoom to the parent's container of the canvas:
<div id="parent_div">
<div id="constructor_div">
<canvas width="600" height="900">
</div>
</div>
<script>
constructor_zoom();
$(window).resize(function() {
constructor_zoom();
});
function constructor_zoom()
{
var parent_width = $('#parent_div').width();
var item_width = $('#constructor_div').width();
var coef = 0.1;
$('.constructor_image').css('zoom', parent_width/item_width - coef);
}
</script>
coef - coefficient to make indents of the canvas from the parent's borders. You may make it zero.
I hope it helps to somebody :-)
I need to add mouse event via Javascript to below code... I have already added touch events in order to test in desktop browsers I need to add mouse events .. I tried adding mouse event to addEventListener but seems to not work I'm not pretty sure what was wrong...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=768px, maximum-scale=1.0" />
<title>rsaCanvas</title>
<script type="text/javascript" charset="utf-8">
window.addEventListener('load',function(){
// get the canvas element and its context
var canvas = document.getElementById('rsaCanvas');
var insertImage = document.getElementById('insert');
var context = canvas.getContext('2d');
//load image and annotation method
var loadData = {
imageLoad: function(){
var img = new Image();
img.src = 'the_scream.jpg';
context.drawImage(img,0,0);
}
};
// create a drawer which tracks touch movements
var drawer = {
isDrawing: false,
touchstart: function(coors){
context.beginPath();
context.moveTo(coors.x, coors.y);
this.isDrawing = true;
},
touchmove: function(coors){
if (this.isDrawing) {
context.lineTo(coors.x, coors.y);
context.stroke();
}
},
touchend: function(coors){
if (this.isDrawing) {
this.touchmove(coors);
this.isDrawing = false;
}
}
};
// create a function to pass touch events and coordinates to drawer
function draw(event){
// get the touch coordinates
var coors = {
x: event.targetTouches[0].pageX,
y: event.targetTouches[0].pageY
};
// pass the coordinates to the appropriate handler
drawer[event.type](coors);
}
// attach the touchstart, touchmove, touchend event listeners.
canvas.addEventListener('touchstart',draw, false);
canvas.addEventListener('touchmove',draw, false);
canvas.addEventListener('touchend',draw, false);
insertImage.addEventListener('click',loadData.imageLoad, false);
// prevent elastic scrolling
document.body.addEventListener('touchmove',function(event){
event.preventDefault();
},false); // end body.onTouchMove
},false); // end window.onLoad
</script>
<style>
#rsaCanvas{border:5px solid #000;}
</style>
</head>
<body>
<div id="container">
<canvas id="rsaCanvas" width="400" height="500">
Sorry, your browser is not supported.
</canvas>
<button id="insert">Insert Image</button>
</div>
</body>
</html>
try this one.
function init () {
// ...
// Attach the mousemove event handler.
canvas.addEventListener('mousemove', ev_mousemove, false);
}
// The mousemove event handler.
var started = false;
function ev_mousemove (ev) {
var x, y;
// Get the mouse position relative to the canvas element.
if (ev.layerX || ev.layerX == 0) { // Firefox
x = ev.layerX;
y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
x = ev.offsetX;
y = ev.offsetY;
}
// The event handler works like a drawing pencil which tracks the mouse
// movements. We start drawing a path made up of lines.
if (!started) {
context.beginPath();
context.moveTo(x, y);
started = true;
} else {
context.lineTo(x, y);
context.stroke();
}
}
source http://dev.opera.com/articles/view/html5-canvas-painting/
if your problem is with insertImage.addEventListener('click',loadData.imageLoad, false); not showing image when u click, it is because
imageLoad: function(){
var img = new Image();
img.src = 'the_scream.jpg';
context.drawImage(img,0,0);
}
Note img.src is async, to draw the image do
img.onload = (function() {
var image = img;
return function() {context.drawImage(image, 0, 0);};
})();